rav*_*vun 9 spring dependency-injection ejb-3.1
我正在尝试将Spring bean注入到EJB中,@Interceptors(SpringBeanAutowiringInterceptor.class)
但是我无法使用beanRefContext.xml
我见过的示例.
这是我的EJB:
@Stateless
@Interceptors(SpringBeanAutowiringInterceptor.class)
public class AlertNotificationMethodServiceImpl implements
AlertNotificationMethodService {
@Autowired
private SomeBean bean;
}
Run Code Online (Sandbox Code Playgroud)
我提供了一个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>
Run Code Online (Sandbox Code Playgroud)
但是,它似乎正在重新创建bean而不是获取现有的ApplicationContext.我最终得到以下异常,因为我的一个bean是ServletContextAware.
java.lang.IllegalArgumentException: Cannot resolve ServletContextResource
without ServletContext
Run Code Online (Sandbox Code Playgroud)
使用时SpringBeanAutowiringInterceptor
,是不是应该获取ApplicationContext而不是创建一个新的?
我也试过更改我的web.xml,所以contextConfigLocation指向beanRefContext.xml,希望它加载我的Spring配置,但我最终得到了与上面相同的异常.
有谁知道如何正确地做到这一点?我看到的示例似乎使用了我正在使用的相同方法,我假设这意味着在调用Interceptor时正在重新创建bean(或者它是如何工作的,我误解了).
ska*_*man 11
使用时
SpringBeanAutowiringInterceptor
,不应该获得ApplicationContext
而不是创建一个新的吗?
是的,这实际上就是它的作用.它使用ContextSingletonBeanFactoryLocator
机制,而机制又将许多ApplicationContext
实例作为静态单例管理(是的,甚至Spring有时也必须求助于静态单例).这些上下文定义于beanRefContext.xml
.
您的困惑似乎源于这些上下文与您的webapp有任何关系的期望ApplicationContext
- 他们没有,他们完全是分开的.因此,您的webapp ContextLoader
是基于bean定义创建和管理上下文app-config.xml
,并ContextSingletonBeanFactoryLocator
创建另一个.除非你告诉他们,否则他们不会沟通.EJB无法掌握webapp的上下文,因为EJB位于该范围之外.
您需要做的是将需要由EJB使用的app-config.xml
bean 移出另一个bean定义文件.这组提取的bean定义将构成一个新的基础ApplicationContext
,它将(a)由EJB访问,(b)将充当webapp上下文的父上下文.
为了激活你的web应用的环境和新的上下文之间的父子链接,你需要额外添加<context-param>
到您的web.xml
叫parentContextKey
.此参数的值应该是beanRefContext.xml
(context
在您的示例中)中定义的上下文的名称.
留在webapp上下文中的bean将能够引用父上下文中的bean,EJB也是如此.但是,EJB将无法在webapp的上下文中引用任何内容.
此外,您不能使用XmlWebApplicationContext
的beanRefContext.xml
,因为那类要求的Web应用程序的认识,并ContextSingletonBeanFactoryLocator
不能提供这种意识.你应该坚持下去ClassPathXmlApplicationContext
.
归档时间: |
|
查看次数: |
14136 次 |
最近记录: |