EJB 3.1: Does it allow injection of beans into res

2020-03-24 06:41发布

问题:

I am using JBoss 6.1 and its not fully EJB 3.1 compliant. As of now, I can't inject an EJB into my Struts action classes (or in any non-Java EE Container-managed class) via @EJB, but will this be possible when the EJB 3.1 specification is fully implemented?

If not, will it be too infeasible to have that due to performance reasons in the foreseeable future?

回答1:

No container will ever be able to inject anything into a non-managed object.

To be able to to inject into an object, the container needs to manage the object's lifecycle, or at least to participate in the management of its lifecycle, so it can get hold of the object at an early stage to do the injection. If an object is created and used without ever being exposed to the container (as i imagine Struts action beans are), then the container never has a chance to inject anything into it. The container is not magic - it can't just detect objects being created all over the JVM and do things to them.

Mikko's answer has a good list of the kinds of objects that will be injectable. Unless actions beans are one of those, no dice, i'm afraid.

Now, having said all that, there is a light at the end of the tunnel: it may well be possible to write an extension for Struts that handles injection. @EJB and @Resource injections correspond fairly straightforwardly to particular JNDI lookups; an extension could reflectively look for annotated fields, then perform the corresponding JNDI lookups and inject the results. CDI injection is even easier, because it has an API specifically aimed at writing extensions. For an example of doing all this, have a look at the Stripes injection enricher, which adds support for @EJB, @Resource, and @Inject to the Stripes web framework.



回答2:

It is not expected to have it with full implementation of specification. This is explained in Java EE specification v6 (EJB 3.1 being kind of sub specification of one part of Java EE 6). Following components are able to inject (specification, Component classes):

  • Servlet: servlets, servlet filters, event listeners
  • JSP: tag handlers, tag library event listeners
  • JSF: scoped managed beans
  • JAX-WS: service endpoints, handlers
  • EJB: beans, interceptors
  • Managed Beans: managed beans
  • CDI: CDI-style managed beans, decorators
  • Java EE Platform: main class (static), login callback handler

Explained in more depth in mentioned specification, pages 68-71.