Reputation: 26
I have tried to inject an Entity EJB(Facade and entity from MySQL database) but it doesn't work depending on the class it is in. I use a Rest webService and it work in the webService class. I use a multi layered architecture and I don't want my EJB to be injected in this webService.
So, this is the @Stateless facade :
public class ActivityEntityFacade extends AbstractFacade<ActivityEntity> {
@PersistenceContext(unitName = "persistance")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public ActivityEntityFacade() {
super(ActivityEntity.class);
}
}
this is the rest webService method working with EJB :
@EJB
private ActivityEntityFacade activityfacade;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{date}")
public List<ActivityEntity> activities(@PathParam("date") String date){
List<ActivityEntity> activityList = activityfacade.findAll();
return activityList;
}
And this is my activityManager which is supposed to work with the EJB and supposed to return this List to another layer :
public class ActivityManager implements Serializable, IActivity {
@EJB
private ActivityEntityFacade activityfacade;
public ActivityManager(){
}
public List<ActivityEntity> selectAll(){
return activityfacade.findAll();
}
}
This snipet return nullPointerException on the activityEntityFacade. Have you any idea why it doesn't work in this case ?
EDIT: the instance of activityManager is created in the previous layer:
class ServActivityConsult implements IActivable{
@Override
public List<ActivityEntity> activityList() {
IActivity managerActivity = new ActivityManager();
return managerActivity.selectAll();
}
public ServActivityConsult(){
}
}
But the error come from return activityfacade.findAll IN ActivityManager in our case.
Upvotes: 0
Views: 839
Reputation: 692121
You're creating an ActivityManager yourself, using new ActivityManager()
. So the basic rules of Java apply: the constructor is called, and since it doesn't affect any value to activityfacade
, this field is set to null.
For dependency injection to happen, you can't create the objects yourself, but get them from the container. So your class should look like
public class ServActivityConsult implements IActivable{
@Inject
private ActivityManager activityManager;
@Override
public List<ActivityEntity> activityList() {
return activityManager.selectAll();
}
}
And this class itself should be injected in a Jersey controller or an EJB.
Upvotes: 1