Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Context Hierarchy with Web Application Context

I'm dealing with a Spring MVC web app that's bootstrapped using a DispatcherServlet. It creates a XmlWebApplicationContext which manages the whole application:

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Now there are some modules that should be loaded at runtime using a ContextSingletonBeanFactoryLocator. Therefore every module has its own ClasspathXmlApplicationContext. So that a module could reference beans from the XmlWebApplicationContext, it should be attached to the XmlWebApplicationContext to form a Context Hierarchy wherein the XmlWebApplicationContext should play the role of the parent and the ClasspathXmlApplicationContext of the module the role of the child context. Unfortunately I'm unable to connect them using

<beans>
    <bean id="moduleContext"
        class="org.springframework.context.support.ClassPathXmlApplicationContext">
        <constructor-arg>
            ...
        </constructor-arg>
        <constructor-arg ref="parentContext" />
    </bean>
</beans>

because I've found no way so far to give the WebApplicationContext the name parentContext. Have I overlooked something or is there a better/easier way to achieve the same in a different fashion?

like image 696
aha Avatar asked May 18 '11 12:05

aha


1 Answers

If you are using annotations, you can do this:

@Inject
private XmlWebApplicationContext context;

@Inject
private List<ClassPathXmlApplicationContext> childs;

@PostConstruct
public void refreshContext() {
    for(ClassPathXmlApplicationContext appContext : childs) {
        appContext.setParent(context);
    }
    context.refresh();
}

You can do it without annotations too, by using the interfaces InitializingBean and ApplicationContextAware.

Edited: childs is autowired by type, so Spring will inject all the bean that are being an instance of ClassPathXmlApplicationContext.

like image 109
Vincent Devillers Avatar answered Oct 16 '22 03:10

Vincent Devillers