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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With