Search code examples
springdependency-injectionstruts2integrationstruts

How Spring is injecting properties in Struts actions, that are not defined in applicationContext.xml


I am in a project having frameworks like Spring 3 + Struts 2 + Hibernate 3. Also it uses spring security.

Spring and Struts is integrated using spring ContextLoaderListener defined in web.xml

<listener>
    <display-name>Spring Initialization</display-name>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

There are several service classes which usually make db calls. like agentserviceprocess is one such class having method like getAgents().

Struts actions have a property and setter getter for each process and those process classes are defined as bean in application-context.xml.

Surprisingly I can not find any bean having action class as class parameter. I mean spring is not controlling the action object instantiation. Then how spring can inject service property objects inside these actions?


Also, I found following entry

<filter>
    <filter-name>struts</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>struts</filter-name>
    <url-pattern>*.action</url-pattern>
    <url-pattern>*.htm</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

Solution

  • For integration with Spring you should use struts2-spring plugin.

    When this plugin is loaded the plugin's configuration is applied to use its own object factory to instantiate action classes.

    When action instanses are built it passes them to Spring for autowiring.

    You should provide getters and setters of properties for being autowired. You have also provide the spring configuration for dependencies.