将 Spring bean 注入 EJB3

2023-11-26

我正在尝试使用以下方法将 Spring beans 注入到 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 配置,但我最终遇到了与上面相同的异常。

有谁知道如何正确执行此操作?我看到的例子似乎使用了与我正在使用的相同的方法,我认为这意味着在调用拦截器时正在重新创建bean(或者它应该如何工作,但我误解了)。


当使用SpringBeanAutowiringInterceptor,它不应该获得ApplicationContext而不是创建一个新的?

是的,这实际上就是它的作用。它使用ContextSingletonBeanFactoryLocator机制,该机制又管理着许多ApplicationContext实例作为静态单例(是的,即使 Spring 有时也必须诉诸静态单例)。这些上下文定义在beanRefContext.xml.

您的困惑似乎源于这些上下文与您的网络应用程序有任何关系的期望ApplicationContext- 他们没有,他们是完全分开的。所以你的网络应用程序ContextLoader正在创建和管理基于 bean 定义的上下文app-config.xml,以及ContextSingletonBeanFactoryLocator创建另一个。除非你告诉他们,否则他们不会沟通。 EJB 无法获取 Web 应用程序的上下文,因为 EJB 位于该范围之外。

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

为了激活 web 应用程序上下文和新上下文之间的父子链接,您需要添加一个额外的<context-param>给你的web.xml called parentContextKey。该参数的值应该是定义在上下文中的上下文的名称beanRefContext.xml (i.e. context,在你的例子中)。

留在 web 应用程序上下文中的 Bean 将能够引用父上下文中的 Bean,EJB 也是如此。但是,EJB 将无法引用 web 应用程序上下文中的任何内容。

另外,您不能使用XmlWebApplicationContext in beanRefContext.xml,因为该类需要了解网络应用程序,并且ContextSingletonBeanFactoryLocator无法提供这种意识。你应该坚持ClassPathXmlApplicationContext there.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 Spring bean 注入 EJB3 的相关文章

随机推荐