Java · OOP, JVM and backend craft

How does dependency injection work in Spring?

Mediumdependency injectionspringiocUpdated Oct 2026
Quiz this track

Short answer

Dependency injection lets a container supply an object's collaborators instead of the object constructing them. Constructor injection makes dependencies explicit, testable and immutable.

Spring's IoC container creates beans, wires their dependencies and manages their lifecycle. Instead of calling new inside a service, the service declares what it needs and the container resolves it. This inverts control over object creation.

java
@Service
public class OrderService {
    private final OrderRepository repository;

    public OrderService(OrderRepository repository) {
        this.repository = repository;
    }
}
A single constructor needs no @Autowired. The dependency is final and cannot be replaced accidentally.

Injection styles and scopes

  • Constructor injection for required dependencies and easier unit testing
  • Setter injection for optional or reconfigurable dependencies
  • Field injection is concise but hides dependencies and complicates tests
  • Singleton is the default scope; prototype creates a new bean per lookup
  • Use @Qualifier or @Primary when several beans match a type

Constructor injection exposes circular dependencies at startup instead of silently creating proxies. If two beans genuinely depend on each other, the design usually needs to change, often by extracting a third collaborator. Lazy injection can break a cycle but does not fix the underlying coupling.

Inject interfaces at architectural boundaries so implementations can be swapped or mocked. Injecting a concrete repository class is fine when there is only one implementation and no meaningful contract.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why is constructor injection preferred?
  2. 2What is the difference between singleton and prototype scope?
  3. 3How do you resolve multiple beans of the same type?
  4. 4What causes a circular dependency and how do you fix it?

Say it in the interview

Spring's container creates and wires beans, so a class declares its collaborators instead of constructing them. I use constructor injection for required dependencies because it makes them explicit, keeps fields final and simplifies tests. I avoid field injection because it hides the dependency graph and encourages circular designs. When multiple beans match, I resolve them with a qualifier or a primary bean.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.