Sub topic 3
Instantiation and dependency injection
This chapter covers the part of a bean's life that runs before any init callback. The container picks a constructor, resolves its arguments, creates the object, and then fills in the remaining dependencies. I assume you know @Component, @Autowired, @Configuration and @Bean, and that you have run a Spring Boot or plain Spring application.
Where this step fits
After the container has a bean definition, it follows the same sequence for each singleton it creates. Instantiation and injection come first. The Aware callbacks, BeanPostProcessor hooks and init callbacks come after them, and later chapters cover those.
Two consequences follow from this order:
- A bean's dependencies are fully created before the bean itself, when they arrive through the constructor.
- Inside a constructor, only constructor arguments are available. Fields and setters are populated after the constructor returns.
How the container instantiates a bean
The container creates an instance in one of three ways:
- It calls a constructor. This is the default for
@Component-style classes. - It calls a factory method. A
@Beanmethod is the usual case, and its parameters are resolved like constructor arguments. - It calls a
FactoryBean. This is a special bean whose job is to produce another object.
For a component class, the container chooses a constructor with these rules:
- If the class has exactly one constructor, the container uses it, and
@Autowiredis optional. - If the class has several constructors, mark exactly one with
@Autowired. - If several constructors exist and none is marked, the container falls back to the no-argument constructor. If there isn't one, startup fails.
import java.time.Clock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Component
class Repo {
}
@Service
class ReportService {
private final Repo repo;
private final Clock clock;
@Autowired
ReportService(Repo repo, Clock clock) {
this.repo = repo;
this.clock = clock;
}
ReportService(Repo repo) {
this(repo, Clock.systemUTC());
}
String describe() {
return "repo=" + repo.getClass().getSimpleName() + ", clock=" + clock.getZone();
}
}This example needs a Clock bean in the context, for example @Bean Clock clock() { return Clock.systemUTC(); }. Without one, startup fails. The second constructor is for plain Java callers and tests, and the container ignores it.
Three injection styles
Spring can deliver a dependency in three ways.
| Style | Injected when | Can the field be `final`? | Typical use |
|---|---|---|---|
| Constructor | During instantiation | Yes | Required dependencies |
| Setter | After instantiation | No | Optional or replaceable dependencies |
| Field (`@Autowired` on a field) | After instantiation | No | Quick tests, legacy code |
Constructor injection is the default recommendation, for four reasons:
- The object can never exist half-built.
- Fields can be
final. - Unit tests can call
newand pass in fakes. - Circular dependencies show up at startup instead of staying hidden.
Setter and field injection both run after the constructor, which causes a common bug:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
class Greeter {
@Autowired
private Repo repo;
Greeter() {
System.out.println("in constructor, repo = " + repo);
}
}This prints in constructor, repo = null. The container has not injected the field yet, so the constructor cannot use it. If construction logic needs a dependency, take it as a constructor parameter. If you can't, wait for an initialization callback, which the next chapters cover.
Choosing among several candidates
Injection by type fails when no bean, or more than one bean, matches. Spring raises NoSuchBeanDefinitionException for zero matches and NoUniqueBeanDefinitionException for several. If several beans match, the container narrows them down in this order:
- Beans marked
@Primary. - A
@Qualifieron the injection point. - A match between the parameter or field name and the bean name.
import java.util.List;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
interface Notifier {
String send(String message);
}
@Component
@Primary
class EmailNotifier implements Notifier {
public String send(String message) {
return "email: " + message;
}
}
@Component("sms")
class SmsNotifier implements Notifier {
public String send(String message) {
return "sms: " + message;
}
}
@Service
class AlertService {
private final Notifier primary;
private final Notifier sms;
private final List<Notifier> all;
AlertService(Notifier primary, @Qualifier("sms") Notifier sms, List<Notifier> all) {
this.primary = primary;
this.sms = sms;
this.all = all;
}
List<String> broadcast(String message) {
return all.stream().map(n -> n.send(message)).toList();
}
}Here primary receives EmailNotifier, sms receives SmsNotifier, and all receives every Notifier bean. Injecting a List or Map<String, Notifier> is the standard way to collect all implementations of an interface. The @Order annotation or the Ordered interface controls the order of list elements.
Optional and deferred dependencies
A required dependency that is missing stops startup, which is usually what you want. For a dependency that may be absent, use one of these:
Optional<T>or@Autowired(required = false)gives younullor an emptyOptionalwhen no bean exists.ObjectProvider<T>resolves the bean on demand. It offersgetIfAvailable(),getIfUnique()andstream().
ObjectProvider also matters for scopes, because it defers the lookup until you call it. A later chapter uses it to inject prototype beans.
Dependency order and `@DependsOn`
The container creates dependencies before the beans that use them, so for normal injection you never manage creation order yourself. When bean A needs bean B to be initialized first but doesn't reference it, for example because B registers a driver as a side effect, declare the relationship explicitly:
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
@Component
@DependsOn("driverRegistrar")
class LegacyClient {
}The container creates driverRegistrar first. On shutdown it destroys LegacyClient before driverRegistrar, which is the reverse order.
Circular dependencies
Suppose A needs B in its constructor and B needs A in its constructor. Neither can be created first.
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Component
class A {
A(B b) {
}
}
@Component
class B {
B(@Lazy A a) {
}
}Without @Lazy, startup fails with BeanCurrentlyInCreationException. With @Lazy on one parameter, the container injects a lightweight proxy for A into B. The proxy looks up the real A on first use, so the cycle breaks.
Setter and field injection can hide a cycle. For singletons, the container can hand out a reference to a bean that is still being created. Spring Boot 2.6 and later disables this by default, and you can re-enable it with spring.main.allow-circular-references=true. Treat a cycle as a design smell and prefer to extract a third class that both beans depend on. Cycles through prototype beans always fail, because there is no shared early reference to expose.
Instantiation through `@Bean` methods
A @Bean method is a factory method. Its parameters are injected the same way as constructor arguments, and the container invokes the method once for a singleton.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class ClientConfig {
@Bean
HttpClientWrapper client(Repo repo) {
return new HttpClientWrapper(repo);
}
@Bean
static SomePostProcessor postProcessor() {
return new SomePostProcessor();
}
}
class HttpClientWrapper {
HttpClientWrapper(Repo repo) {
}
}
class SomePostProcessor implements org.springframework.beans.factory.config.BeanPostProcessor {
}The second method is static on purpose. A BeanPostProcessor must exist before ordinary beans are created. If its @Bean method is an instance method, the container has to create the whole @Configuration class early, and that class then misses processing by other post-processors. Make @Bean methods that return post-processors static. Chapter on BeanPostProcessor returns to this.
Common errors
NoUniqueBeanDefinitionException: more than one bean matches the type. Add@Primary,@Qualifieror a matching parameter name.UnsatisfiedDependencyException: a wrapper that names the constructor parameter or field that could not be resolved. The cause is nested inside it, so read the whole exception chain.NullPointerExceptionin a constructor: you used a field or setter dependency before it was injected.BeanCurrentlyInCreationException: a circular constructor dependency.- Beans not found: the class is outside the component scan path, which starts at the package of the
@SpringBootApplicationor@ComponentScanclass.
Exercise
A class has two constructors and neither carries @Autowired. It has no no-argument constructor. What happens at startup, and what is the smallest change that fixes it?
Show answer
The container cannot decide which constructor to call and startup fails, because with several constructors it falls back to a no-argument constructor and none exists. Annotate exactly one constructor with @Autowired, which tells the container to use it.
Exercise
Why does a field marked @Autowired still read as null inside the class's own constructor, and how do you fix it?
Show answer
The container injects fields after the constructor returns, so the field is still null during construction. Take the dependency as a constructor parameter, or move the code that needs it into an initialization callback that runs after injection.