Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA EE 6 share instances between stateful EJBs

I think I'm having a basic understanding problem here and I hope someone can explain this to me.

Lets say we have a stateful EJB_A and a stateful EJB_B and a sessionscoped ManagedbeanA:

@Stateful
@LocalBean
public class EJB_A {
}

@Stateful
@LocalBean
public class EJB_B {
  @EJB
  EJB_A ejb;
}
@ManagedBean
@SessionScoped
public class ManagedBeanA {
   @EJB
   EJB_A ejb;
}

In the ManagedBeanA, the EJB_A is created. Now when I use the EJB_B, which has the EJB_A as a property, a new instance of the EJB_A is created within the EJB_B. It is not the same instance of EJB_A that was created in the ManagedBeanA before.

I don't understand that, because I thought the whole point of stateful EJBs is, that for each client only one instance is created and shared and managed by the EJB-Container. Can someone please explain this to me? And please also explain how I can achieve that the same instance of an EJB is shared by multiple other EJBs?

Thank you

like image 620
user1727072 Avatar asked Nov 29 '12 20:11

user1727072


1 Answers

Yes, you mixed up different concepts, and different APIS too... I'd rather use @Inject over @EJB and specify the scope of the injected instance..

@Stateful
@LocalBean
public class EJB_A {
}

@Stateful
@LocalBean
public class EJB_B {
  @Inject @SessionScoped
  EJB_A ejb;
}
@ManagedBean
@SessionScoped
public class ManagedBeanA {
   @Inject @SessionScoped
   EJB_A ejb;
}
like image 186
Carlo Pellegrini Avatar answered Nov 15 '22 04:11

Carlo Pellegrini