Sub topic 13
Circular dependencies and common wiring errors
This chapter assumes you know constructor, setter and field injection, stereotype annotations with component scanning, @Configuration with @Bean, and how @Primary and @Qualifier pick a candidate. It covers the errors you will meet when wiring fails, how to read them, and how to fix the cause.
How wiring fails
Spring resolves every dependency while it builds the context. A wiring problem therefore stops startup, usually with a long stack trace. Two habits make these traces easy to handle:
- Read the last
Caused by:line first. It names the real problem. The lines above it only describe where Spring was when the problem appeared. - Find the bean name and the type that Spring could not resolve. The message usually gives both.
The table lists the failures you will see most often.
| Exception or message | Typical cause | Usual fix |
|---|---|---|
| `NoSuchBeanDefinitionException` (wrapped in `UnsatisfiedDependencyException`) | No bean of the required type exists | Add the stereotype annotation or a `@Bean` method, fix the scan package, or check the active profile |
| `NoUniqueBeanDefinitionException` | Several beans match and none is preferred | Use `@Primary`, `@Qualifier`, or inject a collection |
| `BeanCurrentlyInCreationException` | Two or more beans depend on each other | Break the cycle |
| `BeanCreationException` with "No default constructor found" | A class has several constructors and none is marked `@Autowired` | Mark one constructor, or keep only one |
| `IllegalArgumentException: Could not resolve placeholder` | A `@Value("${...}")` key is not defined | Define the property or give a default such as `${port:8080}` |
Circular dependencies
A circular dependency exists when beans need each other, directly or through a chain. OrderService needs InvoiceService, and InvoiceService needs OrderService.
// OrderService.java
@Service
public class OrderService {
private final InvoiceService invoices;
public OrderService(InvoiceService invoices) {
this.invoices = invoices;
}
public int total(String orderId) {
return 100;
}
}// InvoiceService.java
@Service
public class InvoiceService {
private final OrderService orders;
public InvoiceService(OrderService orders) {
this.orders = orders;
}
public String create(String orderId) {
return "Invoice for " + orders.total(orderId);
}
}To build OrderService, Spring first needs an InvoiceService. To build that, it needs an OrderService. Neither can be built first, because a constructor needs its arguments before the object exists. Startup fails with output like this:
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| invoiceService defined in file [InvoiceService.class]
↑ ↓
| orderService defined in file [OrderService.class]
└─────┘
Action:
Relying upon circular references is discouraged and they are prohibited by default.
Update your application to remove the dependency cycle between beans.Why Spring Boot reports it by default
Plain Spring can sometimes get past a cycle when the beans use setter or field injection. It creates one bean, exposes an unfinished early reference to it, and fills in the fields later. Since Spring Framework 6.0, constructor cycles still fail. Spring Boot 2.6 and later also forbids the setter and field case, through the property spring.main.allow-circular-references, which defaults to false.
You can turn the old behavior back on:
spring.main.allow-circular-references=trueTreat this as a temporary workaround for legacy code. A bean that is reachable before it is fully initialized can be observed in a half-built state, and the behavior depends on the order in which Spring happens to create beans.
Fix 1: extract the shared responsibility
A cycle usually means both classes need something that neither should own. Move it into a third bean that both depend on.
// OrderTotals.java
@Component
public class OrderTotals {
public int total(String orderId) {
return 100;
}
}// OrderService.java
@Service
public class OrderService {
private final OrderTotals totals;
public OrderService(OrderTotals totals) {
this.totals = totals;
}
public String summary(String orderId) {
return "Order total: " + totals.total(orderId);
}
}// InvoiceService.java
@Service
public class InvoiceService {
private final OrderTotals totals;
public InvoiceService(OrderTotals totals) {
this.totals = totals;
}
public String create(String orderId) {
return "Invoice for " + totals.total(orderId);
}
}The dependency graph now has direction: both services depend on OrderTotals, and OrderTotals depends on neither. Each class is also easier to test.
Fix 2: invert one direction
If OrderService only needs to tell InvoiceService that something happened, OrderService does not need to hold a reference to it. Publish an application event, or define a small interface such as OrderListener owned by OrderService and implemented by InvoiceService. The dependency then points one way. Collaborators that need only to be told about a change should be decoupled in this manner.
Fix 3: delay one side with @Lazy or ObjectProvider
If a redesign is not possible right now, you can postpone resolving one dependency. With @Lazy on a constructor parameter, Spring injects a proxy and resolves the real bean on first use:
@Service
public class InvoiceService {
private final OrderService orders;
public InvoiceService(@Lazy OrderService orders) {
this.orders = orders;
}
}An ObjectProvider makes the delay explicit, because you ask for the bean when you need it:
import org.springframework.beans.factory.ObjectProvider;
@Service
public class InvoiceService {
private final ObjectProvider<OrderService> orders;
public InvoiceService(ObjectProvider<OrderService> orders) {
this.orders = orders;
}
public String create(String orderId) {
return "Invoice for " + orders.getObject().total(orderId);
}
}Both approaches start up cleanly, but the cycle is still in the design. They also move the failure from startup to runtime if the delayed bean cannot be created. Use them as a bridge, and leave a comment that says why.
Missing beans
NoSuchBeanDefinitionException means no bean of the requested type is registered. Check these causes in order:
- The class has no stereotype annotation (
@Component,@Service,@Repository,@Controller) and no@Beanmethod. - The class is outside the scanned packages.
@SpringBootApplicationscans its own package and the packages below it. A class in a sibling package is ignored. - The bean sits behind a profile or condition that is not active, such as
@Profile("prod"). - The type is an interface with no implementation bean, or the implementation is a class you create with
newin your own code. - A
@Beanmethod exists but its configuration class is not itself picked up.
Parameter 0 of constructor in com.example.AlertService required a bean of type
'com.example.MessageSender' that could not be found.
Action:
Consider defining a bean of type 'com.example.MessageSender' in your configuration.If a dependency is genuinely optional, say so in the code instead of letting startup fail:
@Service
public class AuditService {
private final java.util.Optional<AuditSink> sink;
public AuditService(java.util.Optional<AuditSink> sink) {
this.sink = sink;
}
public void record(String event) {
sink.ifPresent(s -> s.write(event));
}
}ObjectProvider<AuditSink> and @Autowired(required = false) also work. Do not mark a dependency optional just to silence an error. Optional dependencies should be optional in the design.
Ambiguous beans
NoUniqueBeanDefinitionException means more than one candidate matches the type and Spring cannot choose. The message lists the candidate names:
expected single matching bean but found 2: emailSender,smsSenderYou have four options:
- Mark one candidate
@Primaryto make it the default. - Add
@Qualifier("smsSender")at the injection point to choose by name. - Rename the parameter or field to match a bean name. Spring uses it as a last-resort qualifier, but this depends on parameter names being compiled in, so it breaks silently when renamed.
- Inject all candidates with
List<MessageSender>orMap<String, MessageSender>when you want every one of them.
Other errors that look like wiring problems
A null field on an object you created with new
Spring injects only into beans it creates. If you write new NotificationService() in your own code, no injection happens, and a field-injected dependency stays null. Ask the container for the bean, or let Spring inject it into the class that needs it. Constructor injection prevents this error, because the constructor demands the dependency.
Prototype beans inside singletons
A singleton is built once, so a prototype injected into its constructor is also resolved once. Every call then uses the same instance, which defeats the scope. Inject an ObjectProvider<ReportBuilder> and call getObject() when you need a fresh one.
Several constructors
With one constructor, Spring uses it. With several, Spring needs one marked @Autowired. Without a mark it falls back to a no-argument constructor, and if there is none, startup fails with "No default constructor found".
Calling @Bean methods outside a @Configuration class
In a class annotated @Configuration, a call from one @Bean method to another returns the shared singleton, because Spring proxies the class. In a class that is only annotated @Component, such a call runs as a plain Java method and creates a new object each time. Pass the dependency as a method parameter instead, as in notificationService(MessageSender sender). It works in both cases.
Exercise
A Spring Boot 3 application fails at startup with "The dependencies of some of the beans in the application context form a cycle". ReportService takes AuditService in its constructor, and AuditService takes ReportService. Both only use a shared method formatDate. Which fix do you choose, and why not set spring.main.allow-circular-references=true?
Show answer
Move formatDate into a third bean, for example DateFormatter, and make both services depend on it. This removes the cycle and leaves each class with a single clear dependency direction. Setting the property to true would let the application start but would keep the design problem, and the beans could be used in a half-initialized state.
Exercise
An AlertService constructor takes a MessageSender. The context contains the beans emailSender and smsSender, and startup fails with NoUniqueBeanDefinitionException. Name two ways to fix it, and name a way that depends on compiler settings.
Show answer
Mark emailSender with @Primary, or add @Qualifier("smsSender") to the constructor parameter. Naming the constructor parameter smsSender also works as a fallback qualifier, but it depends on parameter names being kept in the compiled class, so it is fragile.