How do you share Spring beans between different Spring contexts?

喜夏-厌秋 提交于 2019-12-04 03:41:54

问题


We have an application which uses Spring BlazeDS integration. So far we have just been using Spring and Flex, and it is working fine. We now have a requirement to add some Spring MVC controllers as well. The Spring BlazeDS documentation states that the way to do this is to declare two sperate contexts in the web.xml, as follows:

<servlet>
    <servlet-name>flex</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>flex</servlet-name>
    <url-pattern>/messagebroker/*</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>spring-mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>spring-mvc</servlet-name>
    <url-pattern>/spring/*</url-pattern>
</servlet-mapping> 

Here is my question: There are Spring beans which are required to be used within both contexts - the spring-mvc one and the flex one. How can one do this - how can one declare a bean (either in xml or by component scanning) in one context and allow it to be shared with beans declared in the other context? Thanks !


回答1:


Create a parent context by using ContextLoaderListener. The DispatcherServlet contexts will automatically become children of that context.

Create your shared beans in the parent context and refer to them in beans in the child contexts.

If you are using <component-scan> make sure you don't accidentally scan classes into multiple contexts. See my answer here.




回答2:


Add this to your web.xml:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/YOUR_APP_CONTEXT.xml</param-value>
</context-param>

Both beans defined via scanning and direct definitions will be available for your BlazeDS and SpringMVC endpoints.



来源:https://stackoverflow.com/questions/10339174/how-do-you-share-spring-beans-between-different-spring-contexts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!