EJB3 Stateful Session Beans with ejbCreate

I had trouble obtaining a stateful session bean using the EJB3 pattern when trying to pass initial data to it. You can use injection to create instances of stateful beans by simply declaring an instance variable in a bean, for example: @EJB MyStatefulLocal mylocal;. But this doesn't allow you to pass any data on creation. The answer is to use a EJBLocalHome interface like in EJB2 but it's a bit complicated with all the annotations. The ejbCreate method from EJB2.1 is called create in the local home interface and called whatever you want in the bean itself (as long as it is annotated with @Init Below is an example. You can download the source here: download source.
/** Local Interface. Dummy interface to enable us to return the Business interface. */
public interface MyStatefulLocalEjb2 extends EJBLocalObject, MyStatefulLocal 
{}

/** Local Business Interface. Put business method definitions here */
public interface MyStatefulLocal
{}

/** Define method(s) which create the EJB. Must be of name create([optional parameters]),  can be anything e.g. createMyBean(). */
public interface MyStatefulLocalHome extends EJBLocalHome
{
   public MyStatefulLocalEjb2 create(MyEntity initialData);
}

/** This is the EJB itself, note that it implements the "Local Business Interface" not the "Local Interface". */
@Stateful
@LocalHome(MyStatefulLocalHome.class)
public class MyStatefulBean implements MyStatefulLocal
{
   /** matches method in {@link MyStatefulLocalHome#create(MyEntity)} */
   @Init
   public void init(MyEntity initialData)
   {
   }
}

/** This shows using it from another session bean or message bean. */
public class SomeBean
{
   @EJB
   private MyStatefulLocalHome home;

   public void obtainStateful()
   {
      MyEntity initialData = new MyEntity();
      MyStatefulLocal myStateful = home.create(initialData);
   }
}

Comments