[英]Spring: Accessing the correct WebApplicationContext with multiple dispatchers declared
我在我的应用程序中声明了两个Spring上下文 - 一个用于Spring-MVC请求,另一个用于Flex / BlazeDS消息代理请求,映射到不同的url模式:
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>flex</servlet-name>
<url-pattern>/messagebroker/*</url-pattern>
</servlet-mapping>
声明了一个公共上下文配置( /WEB-INF/applicationContext.xml
),然后两个上下文中的每一个都分别在spring-mvc-servlet.xml
和flex-servlet.xml
声明了它们自己的配置。
在flex-servlet.xml
我声明了bean,这些bean特定于flex上下文。 但是,当调用进入http://localhost/messagebroker/*
我收到的错误是那些bean不可用。
有问题的代码位于自定义Spring组件中,因此直接引用WebApplicationContext
以访问声明的bean:
public ISerializer getSerializer(Object source,boolean useAggressiveSerialization)
{
ServletContext ctx = FlexContext.getServletContext();
WebApplicationContext springContext = WebApplicationContextUtils.getRequiredWebApplicationContext(ctx);
String serializerBeanName = springContext.getBeanNamesForType(ISerializer.class);
}
当我使用单个上下文运行时,此方法有效。 但是,它还需要支持运行多个上下文的位置。
设置断点,我看到的价值springContext
是根上下文,用一个单一的configLocation - /WEB-INF/applicationContext.xml
我很担心这就是问题 - 因为上面代码所需的ISerializer
是在flex-servlet.xml
声明的。
如何修改上述代码以支持这两种方案? (单个上下文和多个上下文)?
编辑:上面显示的代码位于ManageableComponentFactoryBean中 ,它似乎作为自定义bean工厂运行。 似乎ApplicationContextAware
接口不适用于生成的类。 例如:
<bean id="dpHibernateRemotingAdapterComponentFactory"
class="org.springframework.flex.core.ManageableComponentFactoryBean">
<constructor-arg
value="org.dphibernate.adapters.RemotingAdapter" />
<property name="properties">
<value>
{"dpHibernate" :
{
"serializerFactory" : "org.dphibernate.serialization.SpringContextSerializerFactory"
}
}
</value>
</property>
</bean>
上面引用的代码位于org.dphibernate.serialization.SpringContextSerializerFactory
。 使这个SpringContextSerializerFactory
实现ApplicationContextAware
没有任何影响。
如果flex
是DispatcherServlet
,并且由于某种原因您无法遵循TomásNarros的建议,则可以使用RequestContextUtils.getWebApplicationContext(request)
获取与当前DispatcherServlet
关联的上下文。
还有一个方便的方法RequestContextUtils.getWebApplicationContext(request, ctx)
,如果DispatcherServlet
的一个不可用,它将返回根上下文。
将您的自定义组件声明为Spring Context aware:
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public MyCustomBean implements ApplicationContextAware {
private ApplicationContext springContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
springContext = applicationContext;
}
public ISerializer getSerializer(Object source,boolean useAggressiveSerialization)
{
String serializerBeanName = springContext.getBeanNamesForType(ISerializer.class);
}
}
在bean初始化时,Spring将访问bean的setApplicationContext
方法,并将其创建的上下文作为参数传递。 在那里,您可以随时使用它。
Hrmmmm .....我在Spring / Flex应用程序中使用Spring / Flex集成,几乎只有一个应用程序上下文。 这可能是问题吗? 您在Flex上下文文件中声明的bean不在MVC上下文文件中,并且它们实际上没有被加载?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.