I observed some strange behavior regarding injecting EntityManager.
Following is stripped down version of working code:
Bean.java
@RequestScoped
@Named
public class Bean {
@Inject
private Service service; // +getter
// few variables + getters/setters
public String getMessage() {
return getService().message();
}
}
Service.java
@Stateless
@LocalBean
public class Service {
@PersistenceContext
private EntityManager entityManager; // +getter
public String message() {
return "[" + getEntityManager() + "]";
}
}
cdi.xhtml
<h:body>
<h:outputText value="#{bean.message}" />
</h:body>
But I needed to do some processing, while creating Service. So added following producer method, in factory class.
@Produces
@QService
public Service createService() {
Service service;
service = new Service();
// Some processing
return service;
}
and added same qualifier QService at injection point in class Bean.
@Inject
@QService
private Service service; // +getter
Now, EntityManager is NOT injected in class Service, it remains null.
I’m not able to understand this behavior. Can someone explain this?
I think the problem is this line:
Since
Serviceis an EJB it’s lifecycle is managed by the container. You are allowed to callnewbut I guess you will not get an EJB but a pure java class.Try to inject the Service EJB instead of creating a new instance.