---
title: "struts2与spring结合"
author: "zy77612"
date: "2010-11-20T00:24:27Z"
tags: ["Bean", "Spring", "Struts", "Webwork", "XML"]
categories: ["企业架构"]
slug: "struts2-spring"
draft: false
lastmod: "2010-11-20T00:25:37Z"
id: 816726
url: "https://zy77612.iteye.com/blog/816726"
---

### [struts2与spring结合](http://xiaoqiu369.iteye.com/blog/215795)

转载于在webwork的文章

1 配置struts.properties文件，指定spring作为struts的IoC容器  
struts.objectFactory = spring  
(1)默认的autowiring模式是：by name  
即如果applicationContext.xml文件中的bean id与struts.xml文件中的action name相同，就  
(2)如果要改为其他模式：  
struts.objectFactory.spring.autoWire = name|type|auto|constructor

2 配置web.xml文件，启动Spring侦听器  
&lt;listener&gt;  
&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;  
&lt;/listener&gt;

3 在WEB-INF目录下增加applicationContext.xml文件  
例：  
&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "[http://www.springframework.org/dtd/spring-beans.dtd](http://www.springframework.org/dtd/spring-beans.dtd)"&gt;  
&lt;beans default-autowire="autodetect"&gt;  
&lt;bean id="personManager" class="com.acme.PersonManager"/&gt;  
...  
&lt;/beans&gt;

4 设置由Spring来初始化action  
4.1  在Spring的applicationContext.xml文件中配置bean（即action类）  
4.2  将struts.xml中的action的class属性，由class名改为Spring中定义的bean名  
例如：  
(1)applicationContext.xml中，定义bean id是bar  
&lt;beans default-autowire="autodetect"&gt;  
&lt;bean id="bar" class="com.my.BarClass" singleton="false"/&gt;  
...  
&lt;/beans&gt;  
(2)struts.xml中，action的class="bar"，而不是通常的类名  
&lt;package name="secure" namespace="/secure" extends="default"&gt;  
&lt;action name="bar" class="bar"&gt;  
&lt;result&gt;bar.ftl&lt;/result&gt;  
&lt;/action&gt;  
&lt;/package&gt;