Sunday, August 12, 2007

Struts 2 wired by Spring

Struts 2 is a framework for aiding Java Developers into building their web applications, using Inversion of Control (IoC) and MVC Architecture for a multi-tier architecture.

In this post we will see how to wire your action and service classes in Struts 2 using the spring framework.

To start, if you are using Maven there is a dependency you need to add to your pom file.


When this is done, it is necessary to add a listener to the WEB-INF/web.xml file. This is a spring listener, used to intercept calls and redirect them to the Application Context.


Now, we will need to create the Application Context file for Spring. It will use the configuration information in this file to inject the necessary beans into each needed class. The file format is like below and it should be called WEB-INF/applicationContext.xml. I added some example beans to explain how Struts will later identify these beans and inject them into the Actions being called by the framework.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

<bean id="personService" class="my.service.PersonServiceImpl" />

<bean id="personAction" scope="prototype"
<constructor-arg ref="personService" />


Last, but not least it is necessary to setup the struts.xml file to tell the framework that it should use struts' object factory. The example below will show the entries you need to add to struts.xml file. Setting "struts.objectFactory" to "spring" will force Struts to instantiate the actions using Spring, injecting all the defined dependencies on applicationContext.xml.

<?xml version="1.0" encoding="UTF-8" ?>
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
<constant name="struts.objectFactory" value="spring" />
<constant name="struts.devMode" value="true" />

<package name="person" extends="struts-default">

<action name="list" method="execute" class="personAction">
<result name="input">pages/list.jsp</result>




The "class" attribute for each action alias is set to "personAction", which is the bean id that we defined on applicationContext.xml for the PersonAction class. This is all that is needed to make Struts work with Spring.

Have fun!

1 comment:

lokesh said...

Really nice tutorial.helped me alot.