---
title: "Struts 2整合Spring"
author: "crukor"
date: "2015-03-05T18:45:21Z"
tags: ["Struts2"]
categories: ["编程语言"]
slug: "struts-2-spring"
draft: false
lastmod: "2015-03-05T18:46:18Z"
id: 2189187
url: "https://crukor.iteye.com/blog/2189187"
---

Spring是javaEE领域一个非常优秀的框架，它的主要核心是IoC（Inversion of Control，控制反转）容器和AOP机制。

 

大部分JavaEE应用，都会考虑使用Spring容器来管理应用中的组件，从而保证各组件之间的低耦合。Struts 2框架只是一个MVC框架，只是一个Web层的解决方案，如果不与其他框架整合将会严重影响Struts 2框架功能的发挥。Struts 2通过一种“可插拔式”的插件，实现了与Spring框架的整合。

    

一、添加jar包

将spring.jar（dest路径下，这个文件是Spring框架最全的类库，添加该文件比使用分模块类库更加简单）、commos-loggin.jar复制Web应用的WEB-INF/lib路径下。

    安装Struts 2的Spring插件：将Struts2-spring-plugin-2.3.1.2.jar复制到WEB-INF/lib路径下。

 

二、Spring容器的初始化

    在web.xml文件中增加下一段：

    &lt;!--根据默认配置文件来初始化Spring容器--&gt;

    &lt;listener&gt;

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

    &lt;/listener&gt;

 

     如果应用中的Spring配置文件有多个，则应该采用如下形式的web.xml文件来创建Spring容器。 

&lt;!--指定多个Spring的配置文件--&gt;

&lt;context-param&gt;

  &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;

    &lt;!--多个配置文件之间以,隔开--&gt;

  &lt;param-value&gt;classpath\*:/conf/spring.mvc.xml,/WEB-INF/applicationContext.xml&lt;/param-value&gt;

&lt;/context-param&gt;

&lt;listener&gt;

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

&lt;/listener&gt;

 

    如果没有在web.xml中利用contextConfigLocation指定配置文件，则Spring自动查找WEB-INF路径下的“applicationContext.xml”配置文件。如果无法找到合适的配置文件，Spring将无法正常初始化。

 

 

三、整合流程

    Spring插件提供了一种伪Action，当我们在struts.xml文件中配置Action时，通常需要指定class属性，该属性就是用于创建Action实例的实现类。但Spring插件允许我们知道class属性时，不是指向Action的实际实现类，而是指向Spring容器中的BeanID。整合后的组件协作如图所示：

   
![](http://dl2.iteye.com/upload/attachment/0106/4046/fc3eb123-ffe0-3c38-8789-8cdf660495c5.jpg)  
 

在这种整合策略下，处理用户请求的Action由Spring插件负责创建，但Spring插件创建Action实例时，并不是利用配置Action时指定的class属性来创建该Action实例的，而是从Spring容器中取出对应的Bean实例完成创建的。

 

例如在struts.xml中配置action：

     &lt;!--此Action由Spring负责创建，此处的class属性不是实际处理类 --&gt;

    &lt;atcion name=”login” class=”loginBean”&gt;

      &lt;result name=”welcome”&gt;/WEB-INF/welcome.jsp&lt;/result&gt;

    &lt;/action&gt;