0

I am using Maven framework to build my project and EJB 3.0 is the EJB specification. I have an EJB interface A and its corresponding EJB class B that implements A. The body of class B is shown below:

@Stateless
@TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)
class B implements A{

      @PersistenceContext(unitName = "Draco-PU", type = PersistenceContextType.TRANSACTION)
  EntityManager entityManager;  

      //called post construct
      @PostConstruct
      public init(){

            //body of init method

      }

I have a non-EJB class in a different package under the same project. I want to instantiate class B in this class, so that the init() method and other annotations are automatically referred and I can give explicit call to other methods in the EJB class. Please help.

David
  • 19,577
  • 28
  • 108
  • 128
San
  • 31
  • 1
  • 13

1 Answers1

1

You can't do that. Either the caller of NonEJBClass.someMethod() needs to pass A to someMethod (because the caller injected or looked it up), or someMethod needs to do the lookup itself (probably in one of the "java:" namespaces). Otherwise, you need to change your bean so that it can be used by an unmanaged client, e.g.:

Bean:

@Stateless
@TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW)
class B implements A {
    private EntityManager entityManager;  

    @PersistenceContext(unitName = "Draco-PU", type = PersistenceContextType.TRANSACTION)
    public void setEntityManager(EntityManager em) {
        entityManager = em;
    }

    @PostConstruct
    public init() {
        //body of init method
    }
}

Unmanaged client:

B obj = new B();
obj.setEntityManager(...);
obj.init();

So, you either allow the container to create the object (and it takes care of all the injection and initialization), or you create the object yourself (and then you take care of all the setter calls and initialization).

Brett Kail
  • 33,593
  • 2
  • 85
  • 90
  • Is it not possible to do the lookup in the non-EJB class? – San Oct 25 '12 at 04:36
  • You could do that, but then you're in the awkward position of the EJB performing lookup in its own `java:comp` (managed) and its caller `java:comp` (servlet?). I think that would be too confusing. – Brett Kail Oct 25 '12 at 12:51
  • Sorry, I misread: yes, the non-EJB class can look up the EJB. If the non-EJB class is always called from a servlet, for example, you can declare the EJB reference in the servlet, and then the non-EJB class can look up the EJB reference from `java:comp`. – Brett Kail Oct 25 '12 at 12:52