9

我正在尝试将 Spring bean 注入到 EJB 中,@Interceptors(SpringBeanAutowiringInterceptor.class)但我无法使用beanRefContext.xml我见过的示例使其工作。

这是我的 EJB:

@Stateless
@Interceptors(SpringBeanAutowiringInterceptor.class)
public class AlertNotificationMethodServiceImpl implements
        AlertNotificationMethodService {

    @Autowired
    private SomeBean bean;
}

我提供了一个 beanRefContext.xml 如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="...">

   <!-- Have also tried with ClassPathXmlApplicationContext -->
   <bean id="context"
        class="org.springframework.web.context.support.XmlWebApplicationContext">
        <property name="configLocations" value="/config/app-config.xml" />
   </bean>

</beans>

但是,它似乎是重新创建 bean 而不是获取现有的 ApplicationContext。我最终得到以下异常,因为我的 bean 之一是 ServletContextAware。

java.lang.IllegalArgumentException: Cannot resolve ServletContextResource
without ServletContext

使用时SpringBeanAutowiringInterceptor,不应该获取ApplicationContext而不是创建一个新的吗?

我还尝试更改我的 web.xml,以便 contextConfigLocation 指向 beanRefContext.xml,希望它会加载我的 Spring 配置,但我最终会遇到与上述相同的异常。

有谁知道如何正确地做到这一点?我看到的示例似乎使用了我正在使用的相同方法,我认为这意味着在调用 Interceptor 时正在重新创建 bean(或者它应该如何工作并且我误解了)。

4

1 回答 1

12

使用时SpringBeanAutowiringInterceptor,不应该获取ApplicationContext而不是创建一个新的吗?

是的,这实际上就是它的作用。它使用该ContextSingletonBeanFactoryLocator机制,该机制反过来将许多ApplicationContext实例作为静态单例进行管理(是的,即使是 Spring 有时也不得不求助于静态单例)。这些上下文在 中定义beanRefContext.xml

您的困惑似乎源于期望这些上下文与您的 webapp 有任何关系ApplicationContext——它们没有,它们是完全独立的。因此,您的 webappContextLoader正在创建和管理基于 bean 定义的上下文app-config.xml,并ContextSingletonBeanFactoryLocator创建另一个上下文。除非你告诉他们,否则他们不会交流。EJB 无法掌握 webapp 的上下文,因为 EJB 位于该范围之外。

您需要做的是将您的 EJB 需要使用的 bean 从另一个 bean 定义文件中移出app-config.xml并移入另一个 bean 定义文件。这组提取的 bean 定义将构成一个新的基础ApplicationContext,它将 (a) 由 EJB 访问,并且 (b) 将充当您的 webapp 上下文的父上下文。

为了激活你的 webapp 上下文和新上下文之间的父子链接,你需要在<context-param>你的web.xml被调用的parentContextKey. 此参数的值应该是定义的上下文的名称beanRefContext.xml(即context,在您的示例中)。

留在 webapp 上下文中的 bean 将能够引用父上下文中的 bean,EJB 也一样。但是,EJB 将无法引用 webapp 上下文中的任何内容。

此外,您不能使用XmlWebApplicationContextin beanRefContext.xml,因为该类需要对 webapp 的认识,并且ContextSingletonBeanFactoryLocator无法提供这种认识。你应该坚持在ClassPathXmlApplicationContext那里。

于 2011-03-10T12:49:12.337 回答