Sub topic 13
Circular dependencies and common wiring errors
This chapter assumes you know constructor injection, component scanning, @Bean methods, and how @Primary and @Qualifier choose between candidates. It covers the errors Spring raises when it cannot build the bean graph, and how to fix each one.
Circular dependencies
A circular dependency exists when bean A needs bean B and bean B needs bean A. With constructor injection, Spring cannot build either bean first, because each constructor call needs the other bean to already exist.
@Service
public class OrderService {
private final StockService stock;
public OrderService(StockService stock) {
this.stock = stock;
}
}
@Service
public class StockService {
private final OrderService orders;
public StockService(OrderService orders) {
this.orders = orders;
}
}Starting this application fails with an UnsatisfiedDependencyException that wraps a BeanCurrentlyInCreationException. The message lists the cycle, for example orderService -> stockService -> orderService. Read that chain first. It shows exactly which beans form the loop.
Spring Boot 2.6 and later reject circular references even when they would technically work, such as with setter or field injection. The property spring.main.allow-circular-references=true turns the check off. Treat it as a temporary workaround, because a cycle usually means two classes are too tightly coupled.
Ways to break a cycle
- Extract a third bean. Move the logic both classes share into a new class that both depend on. This is usually the right fix.
- Invert one direction. Have one side publish an event or take a callback, so it no longer holds a reference to the other.
- Use
@Lazyon one parameter. Spring injects a proxy and resolves the real bean on first use. - Switch one side to setter injection. This works only when circular references are allowed, and it hides the design problem.
@Service
public class OrderService {
private final StockService stock;
public OrderService(@Lazy StockService stock) {
this.stock = stock;
}
}@Lazy removes the startup failure but not the coupling, so prefer extracting a third bean.
Missing and ambiguous beans
Most wiring errors come from the type-based lookup you saw in the autowiring chapter.
| Exception | Cause | Typical fix |
|---|---|---|
| `NoSuchBeanDefinitionException` | No bean of the required type exists | Add `@Component` or `@Service`, add a `@Bean` method, or widen the scan |
| `NoUniqueBeanDefinitionException` | Several beans match and none is preferred | Mark one `@Primary`, or use `@Qualifier` |
| `BeanCurrentlyInCreationException` | A cycle was found during creation | Break the cycle as shown above |
| `BeanInstantiationException` | The constructor or factory method threw | Read the nested cause in the stack trace |
Why a bean goes missing
- The class is outside the packages scanned from the
@SpringBootApplicationor@ComponentScanclass. Spring scans that class's package and its sub-packages only. - The class has no stereotype annotation, and no
@Beanmethod returns it. - The bean sits behind a profile or condition that is not active, such as
@Profile("prod")while running with thedevprofile. - The configuration class was never registered with the context.
Spring wraps these failures in UnsatisfiedDependencyException. The outer message names the bean being created, and the Caused by: line near the bottom names the real problem, so read from the bottom up.
@Configuration
public class SenderConfig {
@Bean
public MessageSender emailSender() {
return (to, body) -> System.out.println("email: " + body);
}
@Bean
public MessageSender smsSender() {
return (to, body) -> System.out.println("sms: " + body);
}
}Any bean that injects a plain MessageSender from this configuration fails with NoUniqueBeanDefinitionException. The message lists both candidates, emailSender and smsSender. Adding @Primary to one method, or @Qualifier("smsSender") on the parameter, fixes it.
Exercise
An application fails at startup with BeanCurrentlyInCreationException for orderService -> stockService -> orderService. Both classes use constructor injection. Name two ways to fix it, and say which one you would choose.
Show answer
You can extract the logic both classes share into a third bean, or put @Lazy on one constructor parameter. Setter injection with allow-circular-references=true also works, but it only hides the cycle. Extracting a third bean is the better choice because it removes the cycle instead of working around it.