Reputation: 3
My injected EntityManager is not initiated when used in a member variable. When I use it inside a method, it is initiated.
Is this a problem that has to do with the instantiation time of injected beans in general? Or is it only because I'm using quarkus and hibernate?
@Inject
EntityManager entityManager;
private StudentFacade studentFacade = new StudentFacade(entityManager); //entityManager is null
The variable "entityManager" should be initiated, but it has a null value.
Upvotes: 0
Views: 1760
Reputation: 64079
Quarkus also supports constructor injection, so you could also do something like:
@Singleton
public class MyBean {
final StudentFacade studentFacade;
public MyBean(EntityManager entityManager) {
this.studentFacade = new StudentFacade(entityManager);
}
}
Upvotes: 2
Reputation: 953
The problem is that studentFacade
is initialized upon constructing whatever object holds the entityManage
, but whatever framework you use for DI - injects entityManager
only after object constructing.
So upon initializing of studentFacade
field - entityManager
is still null.
To solve this problem you can delay initializing of studentFacade
variable until after injects. Usually it is accomplished by using some life-cycle hooks, like:
@PostConstruct
public void onConstruct() {
studentFacade = new StudentFacade(entityManager);
}
Example is given for Spring framework but I guess almost the same rules applied to whatever you use.
Upvotes: 1