How do you share Spring beans between different Spring contexts?

We have an application that uses Spring BlazeDS integration. So far, we have just used Spring and Flex, and it is working fine. Now we have a requirement to add several Spring MVC controllers. Spring BlazeDS documentation says that the way to do this is to declare two sperate contexts in web.xml , as shown below:

<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 that should be used in both contexts: spring -mvc and flex are one. How can this be done - how can one declare a bean (either in xml or by scanning components) in one context and allow its sharing with beans declared in another context? Thank you

+4
source share
2 answers

Create a parent context using ContextLoaderListener . DispatcherServlet contexts will automatically become children of this context.

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

If you use <component-scan> , make sure that you do not accidentally look at classes in multiple contexts. See my answer here .

+6
source

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 by scanning and direct definitions will be available for your BlazeDS and SpringMVC endpoints.

+1
source

Source: https://habr.com/ru/post/924024/


All Articles