Consider the following scenario:
public class Car {
@Inject
private Engine engine;
public Car() {
engine.initialize();
}
...
}
Since Car has to be instantiated prior to field injection, the injection point engine is still null during the execution of the constructor, resulting in a NullPointerException.
This problem can be solved either by JSR-330 Dependency Injection for Java constructor injection or JSR 250 Common Annotations for the Java @PostConstruct method annotation.
@PostConstruct
JSR-250 defines a common set of annotations which has been included in Java SE 6.
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.
JSR-250 Chap. 2.5 javax.annotation.PostConstruct
The @PostConstruct annotation allows for the definition of methods to be executed after the instance has been instantiated and all injects have been performed.
public class Car {
@Inject
private Engine engine;
@PostConstruct
public void postConstruct() {
engine.initialize();
}
...
}
Instead of performing the initialization in the constructor, the code is moved to a method annotated with @PostConstruct.
The processing of post-construct methods is a simple matter of finding all methods annotated with @PostConstruct and invoking them in turn.
private void processPostConstruct(Class type, T targetInstance) {
Method[] declaredMethods = type.getDeclaredMethods();
Arrays.stream(declaredMethods)
.filter(method -> method.getAnnotation(PostConstruct.class) != null)
.forEach(postConstructMethod -> {
try {
postConstructMethod.setAccessible(true);
postConstructMethod.invoke(targetInstance, new Object[]{});
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
throw new RuntimeException(ex);
}
});
}
The processing of post-construct methods has to be performed after instantiation and injection have been completed.