IoC and dependency injection
- IoC
- Inversion of Control
Junior Always asked 7 min
On this page
The question
What are inversion of control and dependency injection in Spring?
30-second answer
Inversion of control means a class no longer creates or finds its own dependencies: the framework does. Dependency injection is how Spring does it. You declare what a class needs, usually as constructor parameters, and the container builds the objects and passes them in. Classes depend on abstractions, so they are loosely coupled and easy to test with a mock.
Understand it
The container wires a dependency graph
Step by stepThe container scans your packages and records a bean definition for each annotated class: a recipe. No object exists yet.
View as text
A dependency graph with OrderController at the top, OrderService below it, and OrderRepository and PaymentClient at the bottom. Each box says whether it is only a definition, is waiting for its dependencies, or is built. A line of code below names the call being made.
The container scans your packages and records a bean definition for each annotated class: a recipe. No object exists yet.
It starts with OrderController. The constructor needs an OrderService, which does not exist yet, so that has to come first.
OrderService needs an OrderRepository and a PaymentClient. The container keeps walking down until it reaches beans that need nothing.
OrderRepository and PaymentClient need nothing, so they are built first. Creation always runs from the leaves upward.
With both dependencies ready, the container calls the OrderService constructor and passes them in.
Now it can build OrderController. No class called new on a dependency: the container did. That is the inversion of control.
A second bean asking for OrderService gets the same instance. A singleton bean is created once, then shared from the context.
A dependency graph with OrderController at the top, OrderService below it, and OrderRepository and PaymentClient at the bottom. Each box says whether it is only a definition, is waiting for its dependencies, or is built. A line of code below names the call being made.
The container scans your packages and records a bean definition for each annotated class: a recipe. No object exists yet.
It starts with OrderController. The constructor needs an OrderService, which does not exist yet, so that has to come first.
OrderService needs an OrderRepository and a PaymentClient. The container keeps walking down until it reaches beans that need nothing.
OrderRepository and PaymentClient need nothing, so they are built first. Creation always runs from the leaves upward.
With both dependencies ready, the container calls the OrderService constructor and passes them in.
Now it can build OrderController. No class called new on a dependency: the container did. That is the inversion of control.
A second bean asking for OrderService gets the same instance. A singleton bean is created once, then shared from the context.
Takeaway: You declare what each class needs. The container reads the definitions, builds the graph from the leaves up, and hands every class its dependencies.
Field vs setter vs constructor injection
CompareField injection: Spring sets a private field by reflection. It is short, but the field cannot be final, and new leaves it null.
View as text
The same OrderService written three ways. Two lines of code sit above three rows: whether the field can be final, what happens with plain new in a test, and how visible the required dependencies are.
Field injection: Spring sets a private field by reflection. It is short, but the field cannot be final, and new leaves it null. final field: Not possible. new in a test: NullPointerException. Required deps: Hidden in the class.
Setter injection: Spring calls a method after the constructor. It fits an optional dependency that can change, because the object can exist without it. final field: Not possible. new in a test: Works if you call it. Required deps: Look optional.
Constructor injection: the object cannot exist without its dependencies, the field is final, and a test passes a mock with plain new. One constructor needs no @Autowired. final field: Yes. new in a test: Compiler asks for it. Required deps: In the signature.
The same OrderService written three ways. Two lines of code sit above three rows: whether the field can be final, what happens with plain new in a test, and how visible the required dependencies are.
Field injection: Spring sets a private field by reflection. It is short, but the field cannot be final, and new leaves it null. final field: Not possible. new in a test: NullPointerException. Required deps: Hidden in the class.
Setter injection: Spring calls a method after the constructor. It fits an optional dependency that can change, because the object can exist without it. final field: Not possible. new in a test: Works if you call it. Required deps: Look optional.
Constructor injection: the object cannot exist without its dependencies, the field is final, and a test passes a mock with plain new. One constructor needs no @Autowired. final field: Yes. new in a test: Compiler asks for it. Required deps: In the signature.
Takeaway: Use constructor injection for required dependencies: fields can be final, the object is never half built, and tests need no Spring.
In code
@Service
public class OrderService {
private final OrderRepository repository;
private final PaymentClient payments;
// One constructor: Spring uses it, with no @Autowired
public OrderService(OrderRepository repository, PaymentClient payments) {
this.repository = repository;
this.payments = payments;
}
public void place(Order order) {
payments.charge(order);
repository.save(order);
}
}@Test
void chargesThenSaves() {
var repository = mock(OrderRepository.class);
var payments = mock(PaymentClient.class);
var service = new OrderService(repository, payments);
service.place(new Order());
verify(repository).save(any());
}@Service
class NotificationService {
private final List<Notifier> notifiers; // every Notifier bean, in @Order order
private final ObjectProvider<SmsGateway> sms; // there may be no SmsGateway bean at all
NotificationService(List<Notifier> notifiers, ObjectProvider<SmsGateway> sms) {
this.notifiers = notifiers;
this.sms = sms;
}
void broadcast(String message) {
notifiers.forEach(n -> n.send(message));
sms.ifAvailable(gateway -> gateway.send(message));
}
}Solve it
Startup fails: “The dependencies of some of the beans form a cycle”
After a refactor, the app stops at startup. OrderService takes a CustomerService in its constructor, to check credit,
and CustomerService takes an OrderService, to count a customer’s orders. Fix it without hiding the problem.
- Read the report. Boot prints the cycle:
orderServicetocustomerServiceand back. Neither constructor can run first, because each needs the other already built. - Know why it surfaced now. Field injection used to hide cycles. Since Spring Boot 2.6, circular references are refused by default.
- Find what is really shared. Credit checks need the order count, and the order count needs only the order data. Both depend on order data, not on each other.
- Break the cycle in the design. Move the shared query into a third bean that both use.
@Lazyorspring.main.allow-circular-references=truewould start the app but keep the tangle. - Check. The app starts, and each service is built in a unit test with plain constructors.
interface OrderStats extends Repository<Order, Long> { // the shared need, a Spring Data query
long countByCustomerId(long customerId);
}
@Service
class CustomerService {
private final OrderStats stats;
CustomerService(OrderStats stats) { this.stats = stats; }
boolean hasCredit(long customerId) { return stats.countByCustomerId(customerId) < 10; }
}
@Service
class OrderService {
private final CustomerService customers;
OrderService(CustomerService customers) { this.customers = customers; } // one direction only
}How to answer
- IoC is the principle; dependency injection is the technique Spring uses.
- The container reads bean definitions, then builds the graph from the leaves upward.
- A bean is an object whose lifecycle the Spring container manages.
- Beans are singletons by default, so one instance is shared.
Common mistakes
- Saying a class gets its dependencies by calling
newinside a@Service. - Treating IoC and dependency injection as unrelated ideas, or being unable to say how they relate.
Follow-up questions
What are the types of dependency injection in Spring, and when do you use each?
There are three: constructor, setter and field. Constructor injection is the default for required dependencies. Setter injection fits an optional dependency that may change after creation. Field injection sets a private field by reflection: it is short, but it hides dependencies and needs Spring or reflection to test, so keep it out of application code.
- Only constructor injection allows
finalfields. - Mark an optional dependency with
ObjectProvideror@Autowired(required = false). - Field injection is still common in test classes, where it does little harm.
// Constructor: required
OrderService(OrderRepository repository) { this.repository = repository; }
// Setter: optional
@Autowired(required = false)
void setAudit(AuditLog audit) { this.audit = audit; }
// Field: avoid in application code
@Autowired private OrderRepository repository; See it in the infographic: Field vs setter vs constructor injection
Why is constructor injection preferred over field injection?
A constructor makes dependencies explicit and required, so an object can never exist half built. Fields can be final, which gives safe immutability. A unit test can call new and pass mocks with no Spring. A long parameter list is also a useful warning that the class does too much, while field injection hides that growth.
- With field injection, plain
newleaves the field null, so the failure comes at run time. - The compiler catches a missing constructor argument.
- Lombok
@RequiredArgsConstructorremoves the boilerplate and keeps the benefits.
See it in the infographic: Field vs setter vs constructor injection
What happens when two beans depend on each other?
Startup fails with BeanCurrentlyInCreationException. Since Spring Boot 2.6 this applies to field and setter injection too, because circular references are off by default. Setting spring.main.allow-circular-references=true makes field injection work again, but a constructor cycle still fails, since neither object can exist first. The real fix is a redesign: extract the shared logic into a third bean.
- A cycle is a design smell, usually two classes that should be split differently.
@Lazyon one constructor parameter breaks the cycle by injecting a proxy.- Events are another way to remove a dependency in one direction.
See it in the infographic: The container wires a dependency graph See it in the infographic: Field vs setter vs constructor injection
What is the difference between BeanFactory and ApplicationContext?
BeanFactory is the basic container: it creates and wires beans, lazily, when asked. ApplicationContext extends it and is what you use in practice. It creates singletons eagerly at startup, so wiring errors appear at once, and it adds events, message sources, environment access and automatic post-processor registration. Spring Boot creates an ApplicationContext for you.
- Eager creation means a missing bean fails the startup, not the first request.
@Lazyopts a single bean out of eager creation.- You rarely call
getBeanyourself; injection replaces it.
See it in the infographic: The container wires a dependency graph
Should you inject an interface or a concrete class?
Inject an interface when there are real alternatives, or a boundary you want to keep replaceable, such as a payment gateway. An interface with one implementation forever adds a file and no value, so injecting the class is fine: Mockito can mock it, and Spring Boot's default proxies work on classes. Choose by whether the abstraction earns its place.
- The dependency inversion principle is about depending on abstractions at boundaries, not everywhere.
- Two implementations of one interface need
@Primaryor@Qualifier. - Hexagonal architecture puts its ports, as interfaces, at these boundaries.
See it in the infographic: The container wires a dependency graph
Does a Spring bean always need an annotation on its class?
No. A @Bean method in a @Configuration class registers a bean from code you cannot annotate, such as a library class. Annotations like @Service are only one way to create a bean definition. What makes an object a bean is that the container manages it, not how it was declared.
What happens if you call new OrderService() yourself in a Spring app?
You get a plain object the container knows nothing about. No dependency is injected, and no proxy is applied, so @Transactional and other advice do nothing. With field injection the dependencies stay null, and the first use throws NullPointerException.
How does Spring know which constructor to use?
With a single constructor it uses that one, and no @Autowired is needed. With several, it uses the one marked @Autowired, or falls back to a no-argument constructor if there is one. If neither applies, creating the bean fails at startup.
Check yourself
Show answers
- NullPointerException: Correct. Nothing injected the field, because only the Spring container processes @Autowired.
- Spring injects the field anyway.: Incorrect. Spring does not see objects created with plain new.
- It does not compile.: Incorrect. It compiles, because the no-argument constructor exists. That is the trap.
Show answers
- OrderRepository: Correct. The container cannot call a constructor until its arguments exist, so creation runs from the leaves upward.
- OrderController: Incorrect. Its constructor needs an OrderService, so it cannot run until that bean exists.
- OrderService: Incorrect. It needs the repository to exist before its own constructor can run.
Show answers
- Startup fails.: Correct. Neither constructor can run first, so the flag cannot help. It only lets field and setter cycles work.
- It starts, because the flag allows cycles.: Incorrect. The flag exposes a half-built bean, and a constructor cycle never has one to expose.
- It starts, with one dependency left null.: Incorrect. Spring does not pass null for a required constructor argument.