Sub topic 3
Instantiation and dependency injection
This chapter assumes you know core Java, the basic Spring annotations (@Component, @Autowired, @Configuration, @Bean), and how to run a Spring or Spring Boot application. It covers the two steps that happen before any initialization callback runs: creating the object and injecting its dependencies.
Instantiation comes first
The container turns a bean definition into an object in two steps.
- Instantiate. The container calls a constructor, or a factory method if the bean comes from
@Bean. The result is a raw object with no injected fields. - Populate. The container injects dependencies into fields and setter methods.
Only after both steps does the container run initialization callbacks, which later chapters cover.
Constructor arguments are created first
Constructor injection forces the container to build dependencies before the bean itself. If OrderService needs OrderRepository, the container creates the repository first. A class with a single constructor needs no @Autowired since Spring 4.3.
Fields and setters are different. Injection into them happens after the constructor returns, so injected fields are still null inside the constructor.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
class Repo {
}
@Component
class OrderService {
private final Repo repo;
@Autowired
private Environment env;
OrderService(Repo repo) {
this.repo = repo;
System.out.println("constructor: repo=" + (repo != null) + ", env=" + (env != null));
}
void report() {
System.out.println("later: env=" + (env != null));
}
}
@Configuration
@ComponentScan
class AppConfig {
}
public class Main {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
ctx.getBean(OrderService.class).report();
}
}
}The output is:
constructor: repo=true, env=false
later: env=trueThe constructor sees repo because the container passed it in. It does not see env because field injection has not happened yet.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `NullPointerException` in a constructor | The code uses a field or setter dependency too early | Take the dependency as a constructor parameter, or move the code to an initialization callback |
| `NoSuchBeanDefinitionException` | No bean of the required type is registered | Check component scanning, or add a `@Bean` method |
| `NoUniqueBeanDefinitionException` | More than one bean matches the type | Use `@Qualifier` or `@Primary` |
| `BeanCurrentlyInCreationException` | Two beans need each other through constructors | Break the cycle in the design, or inject one side with `@Lazy` |
Why prefer constructor injection
Constructor injection lets you declare fields final. It makes missing dependencies fail at startup, and it lets you build the class in a unit test with plain new. For the lifecycle, it also means the object is fully usable as soon as the constructor returns.
Exercise
A bean has an @Autowired field named mailer. Its constructor calls mailer.send("started"). Why does startup fail, and how do you fix it?
Show answer
The container calls the constructor before it injects fields, so mailer is still null and the call throws a NullPointerException. Fix it by taking mailer as a constructor parameter. You can also move the call into a @PostConstruct method, which runs after injection.