Struts2 Spring plugin can be called multiple times at startup
I have been writing a web application that has a plugin framework. The plugins needed to be Struts2 and Spring aware so that they would have tight integration into the web application. In order to make things easier I have been using the struts-spring-plugin.jar that comes bundled with the Struts2 download. The problem was that the following happened when my application initialised:
- The Struts2 framework would initialise and call the struts-spring-plugin to set the Spring ApplicationContext;
- My PluginManager would initialise and set the Spring ApplicationContext within Struts so that my plugins Spring beans would be included and could be found by both Struts and Spring;
- The struts-spring-plugin would be called again and overwrite my Spring ApplicationContext that I had just set.
I tried to track down that third call but could find out where it originated from, all I could get is that it came from a class that was instantiated through the sun reflection classes. Once I had figured out the problem the solution is pretty simple. Just create a copy of the org.apache.struts2.spring.StrutsSpringObjectFactory (from the struts-spring-plugin.jar) in your project and modify it as follows:
try {
// Try and set the SpringObjectFactory with the last child of the Spring ApplicationContexts tree from the MyPluginManager.
MyPluginManager myPluginManager = MyPluginManager.getInstance();
setApplicationContext(myPluginManager.getPluginsXmlWebApplicationContext());
} catch (ExceptionMyPluginManagerNotInitialised empmni) {
// We couldn't set the applicationContext with the one from the MyPluginManager so use the default
setApplicationContext(appContext);
}
The MyPluginManager is the class that manages my plugins. When it initialises the plugins it stores the XmlWebApplicationContext used to initialise that plugin. Each plugin has a new XmlWebApplicationContext that has either the ROOT XmlWebApplicationContext or the last pluginXmlWebApplicationContext as the parent. This means that the last pluginXmlWebApplicationContext is the last in the chain of XmlWebApplicationContext and so can see all of the spring beans from the root context AND the plugins. That is the XmlWebApplicationContext that is used in the above codes call to:
setApplicationContext(myPluginManager.getPluginsXmlWebApplicationContext());
Now Struts uses my child XmlWebApplicationContext and not the ROOT XmlWebApplicationContext.
07.03.2009 11:37 - Posted by doahh - Comments: 0 - Java

Comments: