Tag Archives: Injection

Understanding Dependency Injection – Part 3 Contexts

So far this series has covered simple IoC dependency injection as well as bean initialization with @PostConstruct and constructor injection.

In this part we will introduce container managed contextual scopes to Voodoo DI.

A scope defines the life-cycle of a bean, allowing state to be preserved and or shared across multiple interactions. DI frameworks offer a fast variety of build-in and add-on scopes, such as @RequestScoped, @SessionScoped, @ApplicationScoped, etc…

So far Voodoo DI simply maps interfaces, supertypes and the target type directly to the concrete implementations.

//Map Interfaces and Supertypes to concrete implementation.
private final Map types = new ConcurrentHashMap<>();
...
public  T instance(Class clazz) {
    T newInstance = null;
    try {
      Constructor constructor = types.get(clazz).getConstructor(new Class[]{});
      newInstance = constructor.newInstance(new Object[]{});
      processFields(clazz, newInstance);
    } catch (Exception ex) {
      Logger.getLogger(Voodoo.class.getName()).log(Level.SEVERE, null, ex);
      throw new RuntimeException(ex);
    }
    return newInstance;
  }
...

Continue reading Understanding Dependency Injection – Part 3 Contexts

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:

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.
Continue reading Understanding Dependency Injection – Part 2 PostConstruct and Constructor Injection