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.

有帮助吗?

解决方案

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).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top