jakarta-eeservletsstateful-session-bean

Getting @EJB in the context


as discussed here Display username in jsp redirected from a servlet to get the same instance of a Stateful Session Bean, i have to save it in the HttpSession related. It is working good, but in a servlet i did so:

SessionCart cart = (SessionCart) request.getSession().getAttribute("cart");
if (cart==null){
   cart = new SessionCart();}

Where the attribute "cart" is the one where i saved the initialized cart. The problem is that, if the cart was not initialized before, the row cart=new SessionCart(); initialize a bean not related to Context, so the entitymanager got by @PercistenceContext is null. I tried to use the annotation

@EJB
private SessionCart cart;

but this one create a new session cart anyway, without my control (so if i have a cart related to user yet, i create a new one and i trash it... this is not so good). My question is: could i create a new Stateful Session Bean without using annotation @EJB and getting it related to context? So i can control when i want to create it


Solution

  • If I get it correct, you want to initialize your bean lazy.

    To control/create your bean at runtime you could use Instance<Bean> Java EE API

    In your case it would look like that:

    @Inject
    private Instance<SessionCart> sessionCartInstance;
    
    if (cart == null) {
        cart = sessionCartInstance.get();
    }