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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With