I’m using a container-item pattern and I have:
Container to store users:
@Path("/user")
@Stateless
public class UsersResource {
@Context
private UriInfo context;
@EJB
private UserBeanLocal userBean;
public UsersResource() {
}
@GET
@Produces("application/json")
public String getJson(@HeaderParam("authorization") String authorization) {
return userBean.sampleJSON();
}
@Path("{id}")
public UserResource getUserResource(@PathParam("id") String id) {
return UserResource.getInstance(id);
}
}
Item that is representing single user:
@Stateless
public class UserResource {
@EJB
private UserBeanLocal userBean;
private String id;
public UserResource() {
}
private UserResource(String id) {
this.id = id;
}
public static UserResource getInstance(String id) {
return new UserResource(id);
}
@GET
@Produces("application/json")
public String getJson() {
//TODO return proper representation object
return userBean.sampleJSON();
}
}
And bean. It has only one method:
@Local
public interface UserBeanLocal {
String sampleJSON();
}
@Stateless
public class UserBean implements UserBeanLocal {
@Override
public String sampleJSON() {
return "{\"Name\": \"Jan\", \"Lastname\": \"Węglarz\", \"PESEL\": \"47092412341\"}";
}
}
EJB in container works fine but in item returns null. Why?
I’ve tried to return in getJson() something else, for example id, and there was no problem. Everything worked fine. But when I’m returning something using EJB there is null exception.
App deploys on jboss 7 without any problem.
That is because you are creating instance of UserResource by yourself:
Because it is not created by container via JNDI lookup or injection, it is not container managed. Dependency injection can only take place in container managed components.