EJB 3.1 @EJB Injection into POJO

前端 未结 4 1305
清歌不尽
清歌不尽 2020-12-05 08:22

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

相关标签:
4条回答
  • 2020-12-05 08:44

    Yes, use JNDI lookup.

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

    0 讨论(0)
  • 2020-12-05 08:57

    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.

    0 讨论(0)
  • 2020-12-05 09:02

    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.

    0 讨论(0)
  • 2020-12-05 09:02

    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.

    0 讨论(0)
提交回复
热议问题