If I create an EJB3 bean (say a stateless session bean) in an application using Spring 2.5 for DI, how should I inject dependencies from Spring into the bean without coupling the bean to Spring?
I don't know if you consider applying an interceptor as coupling but that's to my knowledge the standard approach. From the Chapter 18. Enterprise Java Beans (EJB) integration of the documentation:
18.3.2. EJB 3 injection interceptor
For EJB 3 Session Beans and Message-Driven Beans, Spring provides a convenient interceptor that resolves Spring 2.5's
@Autowired
annotation in the EJB component class:org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor
. This interceptor can be applied through an@Interceptors
annotation in the EJB component class, or through an interceptor-binding XML element in the EJB deployment descriptor.@Stateless @Interceptors(SpringBeanAutowiringInterceptor.class) public class MyFacadeEJB implements MyFacadeLocal { // automatically injected with a matching Spring bean @Autowired private MyComponent myComp; // for business method, delegate to POJO service impl. public String myFacadeMethod(...) { return myComp.myMethod(...); } ... }
SpringBeanAutowiringInterceptor
by default obtains target beans from aContextSingletonBeanFactoryLocator
, with the context defined in a bean definition file namedbeanRefContext.xml
. By default, a single context definition is expected, which is obtained by type rather than by name. However, if you need to choose between multiple context definitions, a specific locator key is required. The locator key (i.e. the name of the context definition inbeanRefContext.xml
) can be explicitly specified either through overriding thegetBeanFactoryLocatorKey
method in a customSpringBeanAutowiringInterceptor
subclass.
The only other option I'm aware of (extending the EJB 2.x support classes) is much worse from a coupling point of view (and thus doesn't answer your question).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With