EJB 3.1 @EJB Injection into POJO

谁说胖子不能爱 提交于 2019-12-17 15:46:29

问题


With the new EJB 3.1 spec is it possible to inject an EJB into a pojo? I know in EJB 3.0 the @EJB annotation could be used to inject an EJB but this did not work on simple pojos.

If it is not do I have to look the bean up in JNDI as I know you cannot simple use the new keyword.


回答1:


Yes, use JNDI lookup.

Since your POJO is created by you (I assume), the container is not responsible for injecting the dependencies.




回答2:


With the new EJB 3.1 spec is it possible to inject an EJB into a pojo? I know in EJB 3.0 the @EJB annotation could be used to inject an EJB but this did not work on simple pojos.

Injection of EJB into an POJO is possible IF you use JSR-299 (Java Contexts and Dependency Injection) i.e. if your POJO is a CDI managed bean. In that case, you could do:

@Inject MyEJB service

But this is not an EJB 3.1 feature, this comes from CDI. And if you're not using CDI, you'll have to do a lookup.




回答3:


The new EJB spec (3.1) adds the ability to specify global JNDI names for EJBs. This means that you can use them in any bean, anywhere.

You must do an explicit JNDI lookup, however, as an EJB 3.1 container will not know about your POJO.

The only exception, which I'm guessing does not apply to you, is if your POJO is really an application client, in which case provided the field that is to contain the EJB is static, you may apply the @EJB annotation to it. If that's your situation, you should check out the application client rules in the overall Java EE 5 specification.

Finally, Java EE 6, with its inclusion of JSR-299, may allow what you describe to happen in some way; I do not know the spec yet so cannot comment on it.

I hope this all helps.




回答4:


I wonder too if I could inject EJBs into unmanaged objects. See the Weld (JSR 299 reference implementation) documentation for more details.

But you can perform dependency injection by hand inside a repository or factory like this:

@Stateless
public PojoRespository {

  @Inject
  ResourceForPojos resource;
  @PersistenceContext
  private EntityManager em;

  public Pojo findById(Object id) {
    Pojo p = (Pojo) em.find(Pojo.class, id);
    p.setResource(resource); // injects resource
    return p;
  }

}

If you have many methods where injection should be performed, you could use an interceptor.



来源:https://stackoverflow.com/questions/2021370/ejb-3-1-ejb-injection-into-pojo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!