How to customize the StrutsSpringObjectFactory

Introduction

Spring can use its own MVC or integrate other MVC  frameworks. It can for instance integrate with Struts2 by a specific plugin. The plugin overrides the Struts Object Factory providing a way to configure struts actions as beans in the Spring Context. Sometimes some customized behaviour is needed and the spring plugin as it is is not enough. In this case the StrutsSpringObjectFactory which is the core class of the plugin can be extended and the customized version can be configured instead of the default one.

How to provide a customized StrutsSpringObjectFactory

In order to extend the StrutsSpringObjectFactory the buildBean method in the spring struts plugin should be ovverridden. In the following example the buildBean method is overridden and its logic customized to retrieve a bean from a different spring context than the default one, if it does not exist in the default. This spring context is stored in the ServletContext that can be retreived from the default spring application context.

public class CustomSpringObjectFactory extends StrutsSpringObjectFactory {
…

public Object buildBean(String beanName, Map extraContext, 
		boolean injectInternal) throws Exception {

	XmlWebApplicationContext ctx = (XmlWebApplicationContext) 
          this.appContext;

	ClassPathXmlApplicationContext otherCtx = 
          (ClassPathXmlApplicationContext) ctx.
          getServletContext().
          getAttribute("otherSpringContext");

	Object o = null;

	if (this.appContext.containsBean(beanName)) {
	  o = this.appContext.getBean(beanName);
	} else {
	  if (otherCtx != null) {
	    o = otherCtx .getBean(beanName);
	    return o;
	  }
	}

	if (o == null) {
	  Class beanClazz = getClassInstance(beanName);
	  o = buildBean(beanClazz, extraContext);
	}

	if (injectInternal) {
	  injectInternalBeans(o);
	}

	return o;

}

}
…
}

Finally in the struts.properties configuration file the object factory property should be set with the custom implementation:

struts.objectFactory=org.example.CustomStrutsSpringObjectFactory
How to customize the StrutsSpringObjectFactory last modified: 2015-04-28T02:09:12+00:00 by Mario Casari

Leave a Reply

Your email address will not be published. Required fields are marked *