javajbossejbjboss7.xsessioncontext

Session context is null JBOSS 7.1


UPDATE QUESTION:

I used JBOSS Develper Studio 8, JBOS server 7.1 based on jre 1.7 I have one J2EE project with ejb and web projects. In ejb project I have two identical ejb 3.1 In web project I have only one servlet. This servlet call simple test method in first ejb and then in second ejb. First thing in test method is dependency injection for resource session context via this code

@Resource
private SessionContext context;

First ejb works ok, but second (and any following) return null for session context. This is the comlete code:

FirstServlet.java

@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

@EJB
FirstEJB firstEJB = new FirstEJB();
SecondEJB secondEJB = new SecondEJB();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println(firstEJB.helloFirst());
    out.println(secondEJB.helloSecond());   
}
}

FirstEJB.java

@Stateless
public class FirstEJB {

@Resource
private SessionContext contextFirst;

public String helloFirst(){

    System.err.println(contextFirst.toString());

    return "Hello from FirstEJB";    

 }
}

SecondEJB.java

@Stateless
public class SecondEJB {

@Resource
private SessionContext contextSecond;

public String helloSecond(){

   System.err.println(contextSecond.toString());    

   return "Hello from SecondEJB";    

 }
}

Can anybody knows where is the problem.


Solution

  • The first rule for using injection is that your server (otherwise known as the "container") creates the objects that you inject.

    In your case the lifecycle of each EJB instance is under the complete control of the container.

    In your code, the firstEJB instance that is created by you is replaced by another instance that is created by the container. The secondEJB instance remains the one created by you (it's missing the @EJB annotation), so it has not been subjected to proper lifecycle management and has not been fully constructed with it's @Resource injection processed.

    Therefore, a simple change to your servlet code:

    @WebServlet("/FirstServlet")
    public class FirstServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        @EJB
        private FirstEJB firstEJB;
    
        @EJB
        private SecondEJB secondEJB;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            PrintWriter out = response.getWriter();
            out.println(firstEJB.helloFirst());
            out.println(secondEJB.helloSecond());   
        }
    }
    

    should give you the desired result.