Nesting dependencies in a constructor

Suppose I have Spring or JSF beans service classes. I spend these classes in another class. There are still no problems. I can use these input fields in any way.

But using them in the constructor gives me a NullPointerException.

The constructor probably works before the dependency injection happens, and it does not see my input fields. Is there any solution for using dependency injection in the constructor?

+4
source share
2 answers

Obviously, it is impossible to implement anything in an object if this object does not exist. And to exist, the object must be built.

Spring supports constructor injection:

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

Spring also supports @PostConstruct , which allows you to initialize a bean after all dependencies have been entered.

I do not know about JSF.

+3
source

No, you cannot refer to the entered fields in the constructor. The structure must somehow construct your object (call the constructor), and then introduce the dependencies so that they are empty at the time the constructor runs. Instead, you use annotation @PostConstruct to one of your methods and do it initialize:

 class MyBean { @Inject private MyDependency myDep; @PostConstruct public void init() { assert myDep != null; } } 

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

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

or equivalent annotation.

+3
source

Source: https://habr.com/ru/post/1388432/


All Articles