Understanding Dependency Injection – Part 2 PostConstruct and Constructor Injection

In the first part of this series I introduced basic IoC functionality. In this part we will cover @PostConstruct methods and Constructor Injection.

Consider the following scenario:

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.

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.

Voodoo.class V2.5

The processing of post-construct methods has to be performed after instantiation and injection has been completed.

Voodoo.class V2.5

Constructor Injection

JSR-330 constructor injection allows the use of parameterized constructors.

Injectable constructors are annotated with @Inject and accept zero or more dependencies as arguments. @Inject can apply to at most one constructor per class.

@Inject is optional for public, no-argument constructors when no other constructors are present. This enables injectors to invoke default constructors.

JSR-330 @Inject JavaDoc

Instead of directly invoking the no-args constructor for instantiation, the type has to be scanned for constructors annotated with @Inject.

Voodoo.class V2.5

If exactly one injectable constructor is found, VoodooDI attempts to instantiate all required parameters paramType -> instance(paramType) and instantiate the target type with the injectable constructor constructor.newInstance(params).

In this post we extended VoodooDI to support @PostConstruct methods and constructor injection, in the next post of this series we will introduce contextual scopes.

Acknowledgements

I would like to thank Björn Sonntag and Robert Meyer for reviewing my posts.

One thought on “Understanding Dependency Injection – Part 2 PostConstruct and Constructor Injection”

Leave a Reply

Your email address will not be published. Required fields are marked *