Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency injection in Constructor

Suppose that I have Spring service classes or JSF beans. I wire these classes in another class. There are no problems till now. I can use these injected fields in any method.

But, using them in the constructor gives me a NullPointerException.

Probably the constructor runs before dependency injection happens, and it doesn't see my injected fields. Is there any solution to use dependency injection in a constructor?

like image 450
Ahmet DAL Avatar asked Dec 29 '11 09:12

Ahmet DAL


2 Answers

No you cannot refer to injected fields in the constructor. The framework must construct your object somehow (call a constructor) and then inject dependencies so they are empty during constructor execution. What you usually do instead is applying @PostConstruct annotation to one of your methods and perform initialization there:

class MyBean {
  @Inject 
  private MyDependency myDep;

  @PostConstruct
  public void init() {
    assert myDep != null;
  }
}

In case of spring xml configuration you can use init-method="init" instead of @PostConstruct in your <bean> definition. Alternatively you can use constructor injection, in xml:

<bean id="myBean" class="my.package.MyBean">
  <constructor-arg ref="myDependency/>
</bean>

or annotation equivalent.

like image 90
mrembisz Avatar answered Oct 12 '22 21:10

mrembisz


Obviously, it's not possible to inject anything in an object if this object doesn't exist. And to exist, an object must be constructed.

Spring supports constructor injection:

@Autowired
public SomeService(SomeDependency dep) {
    ...

Spring also supports @PostConstruct, which allows initializing a bean after all the dependencies have been injected.

Don't know about JSF.

like image 36
JB Nizet Avatar answered Oct 12 '22 20:10

JB Nizet