How to customize the StrutsSpringObjectFactory


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) 

	ClassPathXmlApplicationContext otherCtx = 
          (ClassPathXmlApplicationContext) ctx.

	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) {

	return o;



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

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 *