---
title: "整合 Spring 和 Strust2 一起工作"
author: "csevan"
date: "2008-12-02T09:42:00Z"
tags: []
slug: "spring-strust2"
draft: false
lastmod: "2008-12-02T09:42:00Z"
id: 284634
url: "https://csevan.iteye.com/blog/284634"
---

**关键字: struts2 spring**

在Struts2中整合Spring的IoC支持是一件十分简单的事情。让我们一步一步来实现：  
1）复制struts2-spring-plugin-x-x-x.jar和相应的spring.jar到/WEB-INF/lib目录下。  
2）在struts.properties中设置struts.objectFactory属性值

struts.properties

1. struts.objectFactory = spring

或者是在XML文件中进行常量配置

struts.xml

1. &lt;struts&gt;
2. &lt;constant name="struts.objectFactory" value="spring" /&gt;
3. &lt;/struts&gt;

3）配置Spring监听器

web.xml

1. &lt;listener&gt;
2. &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
3. &lt;/listener&gt;

通过Spring配置来注册对象

applicationContext.xml

1. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
2. &lt;!DOCTYPE beans PUBLIC
3. "-//SPRING//DTD BEAN//EN"
4. "http://www.springframework.org/dtd/spring-beans.dtd"&gt;
5. &lt;beans default-autowire="autodetect"&gt;
6. &lt;bean id="hello" class="hpfyeah.struts2.spring.HelloWorldAction"/&gt;
7. &lt;/beans&gt;

当然你也可以拥有更多的Spring配置文件。在web.xml中进行下列设置，从而使Spring的ApplicationContext通过匹配所给定模式的文件来初始化对象

web.xml

1. &lt;!-- 用来定位Spring XML文件的上下文配置 --&gt;
2. &lt;context-param&gt;
3. &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
4. &lt;param-value&gt;
5. /WEB-INF/applicationContext-\*.xml,classpath\*:applicationContext-\*.xml
6. &lt;/param-value&gt;
7. &lt;/context-param&gt;

4）修改你的Struts配置文件

struts.xml

01. &lt;!DOCTYPE struts PUBLIC
02. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
03. "http://struts.apache.org/dtds/struts-2.0.dtd"&gt;
04. &lt;struts&gt;
05. &lt;include file="struts-default.xml"/&gt;
06. &lt;package name="default" extends="struts-default"&gt;
07. &lt;action name="pureStruts" class="hpfyeah.struts2.spring.HelloWorldAction"&gt;
08. &lt;result&gt;hello.jsp&lt;/result&gt;
09. &lt;/action&gt;
10. &lt;action name="springStruts" class="hello"&gt;
11. &lt;result&gt;hello.jsp&lt;/result&gt;
12. &lt;/action&gt;
13. &lt;/struts&gt;

默认情况下，Spring从上面显示的applicationContext.xml文件中寻找为hello所做的配置

5）好了，现在你的Struts2和Spring就能正常的一起工作了。有几个配置技术点需要详细说明下：  
**装配模式**。你可以通过设置修改struts.properties中下列属性的值来改变装配模式。

**name** 按照你的action的属性的名字和Spring里的bean的名字匹配，如果匹配就自动装配。这是**缺省的** **type** 按照你的action的属性的类型，在Spring注册的bean中查找，如果相同就自动装配。这需要你在Spring中仅注册了一个此类型的bean **auto** Spring会试图自动监测来找到最好的方法自动装配你的action **constructor** Spring会自动装配bean的构造函数的参数

**是否使用类缓存**。你可以通过设置修改struts.properties中下列属性的值来改变是否使用Spring自身的类缓存机制。可以设定的值为true或false，默认为true。

struts.properties

1. struts.objectFactory.spring.useClassCache = false