如果我在使用 Spring 2.5 作为 DI 的应用程序中创建一个 EJB3 bean(比如说无状态 session bean),我应该如何在不将 bean 耦合到 Spring 的情况下将 Spring 的依赖项注入(inject)到该 bean 中?
最佳答案
我不知道您是否考虑将拦截器用作耦合,但据我所知这是标准方法。来自Chapter 18. Enterprise Java Beans (EJB) integration文档:
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.
我所知道的唯一其他选择(扩展 EJB 2.x 支持类)从耦合的角度来看要糟糕得多(因此无法回答您的问题)。
另见
关于java - 如何使用 Spring 2.5 将资源注入(inject) EJB3 bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3489168/