Brabster Brabster - 5 months ago 34
Java Question

How to inject resources into EJB3 beans with Spring 2.5?

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.

public class MyFacadeEJB implements MyFacadeLocal {

    // automatically injected with a matching Spring bean
    private MyComponent myComp;

    // for business method, delegate to POJO service impl.
    public String myFacadeMethod(...) {
        return myComp.myMethod(...);

SpringBeanAutowiringInterceptor by default obtains target beans from a ContextSingletonBeanFactoryLocator, with the context defined in a bean definition file named beanRefContext.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 in beanRefContext.xml) can be explicitly specified either through overriding the getBeanFactoryLocatorKey method in a custom SpringBeanAutowiringInterceptor 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).

See also