How can I use same EJB in two different CDI beans and retrieve the values set from one bean into the another?

StackOverflow https://stackoverflow.com/questions/19134250

  •  30-06-2022
  •  | 
  •  

Вопрос

I have a stateful session bean where a list is maintained:

@Stateful
public class CartDAO{

    private List<ShoppingCart> tempCart;
    public void add(ShoppingCart shoppingCart){
        tempCart.add(shoppingCart);
    }

    public List<ShoppingCart> getCart(){
        return tempCart;
    }

    @PostConstruct
    public void init(){
        tempCart = new ArrayList<>();
    }
}

Controller1 to add to the cart:

@Named
@SessionScoped
public class Controller1 implements Serializable {
        @EJB
        CartDAO cartDao;
        public String addToShoppingCart() {
        cartDao.add(shoppingCart);
        }
}

Now, i want to ask you could i get the added items to the list from another cart?

 @Named
    @SessionScoped
    public class Controller2 implements Serializable {
            @EJB
            CartDAO cartDao;
            public String getShoppingCart() {
            System.out.println(cartDao.getCart());//returns null
            }
    }

Obviously the above code returns null.

How do I retrieve the list from another controller. Any help will be much appreciated.

Это было полезно?

Решение

I don't see any obvious mistake here (are you sure that you don't call Controller2#getShoppingCart() before adding any items do your CartDAO?) but here are couple of my notions

  • you should have your CartDAO implement some interface or make it @LocalBean
  • all stateful beans should have method annotated with @Remove so you can clean the resources used in the bean (close datasources and son) and bean will be removed from the memory after this call
  • now it's recommended to use @Inject everywhere instead of @EJB, it's the same (you have to use @EJB only when you inject remote beans)

And also one point, if the System.out.println(cartDao.getCart()); returns null than it means the @PostConstruct haven't been called which is strange. Can you provide some more info about container and your environment?Also show us imports, this is big source of mistakes.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top