http://www.itzhai.com/spring-and-struts2-integration-of-the-two-solutions.html
Struts2与Spring整合的方案一:
(1)将struts2-spring-plugin-x-x-x.jar复制到工程的WEB-INF/lib目录下,在该插件包中有个struts-plugin.xml文件,该文件的默认配置如下:
<struts> <bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory" /> <!-- Make the Spring object factory the automatic default --> <constant name="struts.objectFactory" value="spring" /> <package name="spring-default"> <interceptors> <interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/> <interceptor name="sessionAutowiring" class="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor"/> </interceptors> </package> </struts>
(2)在web.xml中配置Spring的监听器:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml,/WEB-INF/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
(3)修改Struts.xml配置文件:
在配置Action时,需要将class属性和Spring配置文件中的相对应的Action的bean的Id的属性保持一致,系统即可通过Spring来装配和管理Action。
如果action包含了Service层的对象:
private StudentInfoServiceImpl studentInfoService;
则需要添加set方法,才可以使用Spring依赖注入:
public void setStudentInfoService(StudentInfoServiceImpl studentInfoService) { this.studentInfoService = studentInfoService; }
如果action在struts.xml如下配置:
<action name="studentRegister" class="studentRegisterAction"> <result name="result">/WEB-INF/exam/result.jsp </result> <result name="input">/WEB-INF/exam/error.jsp </result> <interceptor-ref name="excludeParamsStack" /> </action>
则在applicationContext.xml文件中该Action的配置如下:
<bean id="studentRegisterAction" class="com.exam.actions.StudentRegisterAction" scope="prototype"> <property name="studentInfoService"> <ref bean="studentInfoService" /> </property> </bean>
Struts2与Spring整合的方案二:
前面两个步骤和方案一的一样;
在配置struts.xml文件时,Action的class为该Action的类路径,而在applicationContext.xml配置文件中不需要添加Action的bean配置。这样,当我们使用Action类时,由于studentInfoService已经配置了相关的bean,所以会自动装配。
studentInfoService的配置:
<bean id="studentInfoService" class="com.exam.service.StudentInfoServiceImpl"> <constructor-arg> <ref bean="studentInfoDAO" /> </constructor-arg> </bean>
Action在struts.xml中的配置如下:
<action name="studentRegister" class="com.exam.actions.StudentRegisterAction"> <result name="result">/WEB-INF/exam/result.jsp </result> <result name="input">/WEB-INF/exam/error.jsp </result> <interceptor-ref name="excludeParamsStack" /> </action>