开发者

How to define the constructor of an EJB3 session bean

I'm creating an EJB3 module which tries to respect a specific facade/implementation design pattern. My facade should be totally EJB free.

I have 2 classes in this module: an entity bean and a session bean, which is the manager of this entity. The manager contains an EntityManager attribute.

I also have a factory which instantiates my manager bean, but this factory isn't aware of the manager's implementation (thus doesn't know about EJB). The factory can only retrieve the name of the manager's class using a property file. The factory will the开发者_高级运维n instantiate the manager:

Class lClass = Class.forName (lClassName);
corporateActionManager = (ICorporateActionManager) lClass.newInstance();

My question is: can I declare a constructor in my manager's implementation, and then, inside that constructor, initialize my EntityManager ?

Normally, I would just use the @PersistenceContext annotation above the EntityManager:

@PersistenceContext(unitName = "my_persistence_unit")
private EntityManager em;

But apparently this doesn't work when the class is directly instantiated.

I tried something like this:

public CorporateActionManagerImpl() {
    Context jndi;
    try {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("my_persistence_unit")
    em = emf.createEntityManager();
    } catch (NamingException e1) {
    e1.printStackTrace();
    }
} 

But then I get a NoInitialContextException, apparently my JNDI context isn't correctly initialized.

Could anyone help me out here?

Thanks


I ended up creating another "manager" class, that would encapsulate the session bean and initializing it in the constructor.

It does add another layer, but in the end it's much easier to sort out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜