---
title: "在Struts 2中实现IoC (Struts 2.0系列之八)"
author: "derpvail"
date: "2008-08-30T12:25:00Z"
tags: []
slug: "struts-2-ioc-struts-2-0"
draft: false
lastmod: "2008-08-30T12:25:00Z"
id: 260965
url: "https://derpvail.iteye.com/blog/260965"
---

[在Struts 2中实现IoC](http://www.blogjava.net/max/archive/2006/12/28/90548.html)

IoC(Inversion of Control，以下译为控制反转）随着Java社区中轻量级容器（Lightweight Contianer）的推广而越来越为大家耳熟能详。在此，我不想再多费唇舌来解释“什么是控制反转”和“为什么需要控制反转”。因为互联网上已经有非常多的文章对诸如此类的问题作了精彩而准确的回答。大家可以去读一下Rod Johnson和Juergen Hoeller合著的《[Expert one-on-one J2EE Development without EJB](http://www.wrox.com/books/0764558315.shtml)》或Martin Fowler所写的《[Inversion of Control Containers and the Dependency Injection pattern](http://www.martinfowler.com/articles/injection.html)》。

言归正传，本文的目的主要是介绍在Struts 2中实现控制反转。

## 历史背景

众所周知，Struts 2是以Webwork 2作为基础发展出来。而在Webwork 2.2之前的Webwork版本，其自身有一套控制反转的实现，Webwork 2.2在[Spring 框架](http://www.springframework.org/)的如火如荼发展的背景下，决定放弃控制反转功能的开发，转由Spring实现。值得一提的是，Spring确实是一个值得学习的框架，因为有越来越多的开源组件（如[iBATIS](http://ibatis.apache.org/)等）都放弃与Spring重叠的功能的开发。因此，Struts 2推荐大家通过Spring实现控制反转。

## 具体实现

首先，在开发环境中配置好Struts 2的工程。对这部分仍然有问题的朋友，请参考我的早前的文章。

然后，将所需的Spring的jar包加入到工程的构建环境（Build Path）中，如下图1所示：

![图1 所依赖的Spring的jar包](http://www.blogjava.net/images/blogjava_net/max/18760/r_pic1.gif)  
图1 所依赖的Spring的jar包

本文使用的是Spring 2.0，Spring强烈建议大家在使用其jar包时，只引用需要的包，原因是Spring是一个功能非常强大的框架，其中有些功能是您不需要的；而且Spring提倡的是“按需所取”，而不是EJB的“爱我就要爱我的一切”。当然，如果你怕麻烦或者是不清楚每个包的作用，引用一个Spring的总包也未尝不可。

接下来，就要修改WEB-INF\\web.xml文件了，内容为：

&lt;? xml version="1.0" encoding="UTF-8" ?&gt;  
&lt; web-app version ="2.4" xmlns ="http://java.sun.com/xml/ns/j2ee"  
    xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation ="http://java.sun.com/xml/ns/j2ee   
    http://java.sun.com/xml/ns/j2ee/web-app\_2\_4.xsd" &gt;

    &lt; display-name &gt; Struts 2 IoC Demo &lt;/ display-name &gt;

    &lt; filter &gt;  
        &lt; filter-name &gt; struts-cleanup &lt;/ filter-name &gt;  
        &lt; filter-class &gt;  
            org.apache.struts2.dispatcher.ActionContextCleanUp  
        &lt;/ filter-class &gt;  
    &lt;/ filter &gt;

    &lt; filter &gt;  
        &lt; filter-name &gt; struts2 &lt;/ filter-name &gt;  
        &lt; filter-class &gt;  
            org.apache.struts2.dispatcher.FilterDispatcher  
        &lt;/ filter-class &gt;  
    &lt;/ filter &gt;

    &lt; filter-mapping &gt;  
        &lt; filter-name &gt; struts-cleanup &lt;/ filter-name &gt;  
        &lt; url-pattern &gt; /* &lt;/ url-pattern &gt;  
    &lt;/ filter-mapping &gt;

    &lt; filter-mapping &gt;  
        &lt; filter-name &gt; struts2 &lt;/ filter-name &gt;  
        &lt; url-pattern &gt; /* &lt;/ url-pattern &gt;  
    &lt;/ filter-mapping &gt;

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

    &lt; welcome-file-list &gt;  
        &lt; welcome-file &gt; index.html &lt;/ welcome-file &gt;  
    &lt;/ welcome-file-list &gt;  
&lt;/ web-app &gt;

清单1 WEB-INF\\web.xml

大家一看便知道，主要是加入Spring的ContextLoaderListener监听器，方便Spring与Web容器交互。

紧接着，修改Struts.properties文件，告知Struts 2运行时使用Spring来创建对象（如Action等），内容如下：

struts.objectFactory = spring

清单2 classes\\struts.properties

再下来，遵循Spring的原则——面向接口编程，创建接口ChatService，代码如下：

![](http://www.blogjava.net/Images/OutliningIndicators/None.gif) package tutorial;  
![](http://www.blogjava.net/Images/OutliningIndicators/None.gif)  
![](http://www.blogjava.net/Images/OutliningIndicators/None.gif) import java.util.Set;  
![](http://www.blogjava.net/Images/OutliningIndicators/None.gif)  
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedBlockStart.gif)![](http://www.blogjava.net/Images/OutliningIndicators/ContractedBlock.gif) public interface ChatService ![](http://www.blogjava.net/Images/dot.gif) {  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)    Set &lt; String &gt; getUserNames();  
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedBlockEnd.gif)}

清单3 tutorial.ChatService.java

然后，再创建一个默认实现ChatServiceImpl，代码如下：

![](http://www.blogjava.net/Images/OutliningIndicators/None.gif) package tutorial;  
![](http://www.blogjava.net/Images/OutliningIndicators/None.gif)  
![](http://www.blogjava.net/Images/OutliningIndicators/None.gif) import java.util.HashSet;  
![](http://www.blogjava.net/Images/OutliningIndicators/None.gif) import java.util.Set;  
![](http://www.blogjava.net/Images/OutliningIndicators/None.gif)  
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedBlockStart.gif)![](http://www.blogjava.net/Images/OutliningIndicators/ContractedBlock.gif) public class ChatServiceImpl implements ChatService ![](http://www.blogjava.net/Images/dot.gif) {  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)  
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://www.blogjava.net/Images/OutliningIndicators/ContractedSubBlock.gif)     public Set &lt; String &gt; getUserNames() ![](http://www.blogjava.net/Images/dot.gif) {  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)        Set &lt; String &gt; users = new HashSet &lt; String &gt; ();  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)        users.add( " Max " );  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)        users.add( " Scott " );  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)        users.add( " Bob " );  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)         return users;  
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)  
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedBlockEnd.gif)}

清单4 tutorial.ChatServiceImpl.java

接下来，就该新建Action了。tutorial.ChatAction.java的代码如下：

![](http://www.blogjava.net/Images/OutliningIndicators/None.gif) package tutorial;  
![](http://www.blogjava.net/Images/OutliningIndicators/None.gif)  
![](http://www.blogjava.net/Images/OutliningIndicators/None.gif) import java.util.Set;  
![](http://www.blogjava.net/Images/OutliningIndicators/None.gif)  
![](http://www.blogjava.net/Images/OutliningIndicators/None.gif) import com.opensymphony.xwork2.ActionSupport;  
![](http://www.blogjava.net/Images/OutliningIndicators/None.gif)  
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedBlockStart.gif)![](http://www.blogjava.net/Images/OutliningIndicators/ContractedBlock.gif) public class ChatAction extends ActionSupport ![](http://www.blogjava.net/Images/dot.gif) {  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)     private static final long serialVersionUID = 8445871212065L ;   
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)      
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)     private ChatService chatService;  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)     private Set &lt; String &gt; userNames;  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)  
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://www.blogjava.net/Images/OutliningIndicators/ContractedSubBlock.gif)     public void setChatService(ChatService chatService) ![](http://www.blogjava.net/Images/dot.gif) {  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)         this .chatService = chatService;  
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)      
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://www.blogjava.net/Images/OutliningIndicators/ContractedSubBlock.gif)     public Set &lt; String &gt; getUserNames() ![](http://www.blogjava.net/Images/dot.gif) {  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)         return userNames;  
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)      
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)    @Override  
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://www.blogjava.net/Images/OutliningIndicators/ContractedSubBlock.gif)     public String execute() ![](http://www.blogjava.net/Images/dot.gif) {  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)        userNames = chatService.getUserNames();  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)         return SUCCESS;  
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://www.blogjava.net/Images/OutliningIndicators/InBlock.gif)      
![](http://www.blogjava.net/Images/OutliningIndicators/ExpandedBlockEnd.gif)}

清单5 tutorial.ChatAction.java

ChatAction类使用属性（Getter/Setter）注入法取得ChatService对象。

然后，配置Spring的applicationContext.xml（位于WEB-INF下）文件，内容如下：

&lt;? xml version="1.0" encoding="UTF-8" ?&gt;  
&lt; beans xmlns ="http://www.springframework.org/schema/beans"  
    xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd" &gt;  
    &lt; bean id ="chatService" class ="tutorial.ChatServiceImpl" /&gt;  
    &lt; bean id ="chatAction" class ="tutorial.ChatAction" scope ="prototype" &gt;  
        &lt; property name ="chatService" &gt;  
            &lt; ref local ="chatService" /&gt;  
        &lt;/ property &gt;  
    &lt;/ bean &gt;  
&lt;/ beans &gt;

清单6 WEB-INF\\applicationContext.xml

上述代码有二点值得大家注意的：

1. Struts 2会为每一个请求创建一个Action对象，所以在定义chatAction时，使用scope="prototype"。这样Spring就会每次都返回一个新的ChatAction对象了；
2. 因为ChatServiceImpl被配置为默认的scope（也即是singleton，唯一的），所以在实现时应保证其线程安全（关于编写线程安全的代码的讨论已经超出本文的范围，更超出了本人的能力范围，大家可以参考Addison Wesley Professional出版的《[Java Concurrency in Practice](http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601)》）。

接下来，在classes/struts.xml中配置Action，内容如下：

&lt;! DOCTYPE struts PUBLIC  
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
        "http://struts.apache.org/dtds/struts-2.0.dtd" &gt;  
&lt; struts &gt;  
    &lt; include file ="struts-default.xml" /&gt;      
      
    &lt; package name ="Struts2\_IoC" extends ="struts-default" &gt;  
        &lt; action name ="Chat" class ="chatAction" &gt;  
            &lt; result &gt; /UserList.jsp &lt;/ result &gt;  
        &lt;/ action &gt;  
    &lt;/ package &gt;      
&lt;/ struts &gt;

清单7 classes\\struts.xml

这里的Action和平常不同的就是class属性，它对应于Spring所定义的bean的id，而不是它的类全名。

最后，让我们看看/UserList.jsp，内容如下：

&lt;% @ page contentType = " text/html; charset=UTF-8 " %&gt;  
&lt;% @ taglib prefix = " s " uri = " /struts-tags " %&gt;  
&lt; html &gt;  
&lt; head &gt;  
    &lt; title &gt; User List &lt;/ title &gt;  
&lt;/ head &gt;

&lt; body &gt;  
    &lt; h2 &gt; User List &lt;/ h2 &gt;  
    &lt; ol &gt;  
    &lt; s:iterator value ="userNames" &gt;  
        &lt; li &gt;&lt; s:property /&gt;&lt;/ li &gt;  
    &lt;/ s:iterator &gt;  
    &lt;/ ol &gt;  
&lt;/ body &gt;  
&lt;/ html &gt;

清单8 /UserList.jsp

大功告成，分布运行应用程序，在浏览器中键入[http://localhost:8080/Struts2\_IoC/Chat.action](http://localhost:8080/Struts2_IoC/Chat.action)，出现如图2所示页面：

![图2 /ListUser.jsp](http://www.blogjava.net/images/blogjava_net/max/18760/r_pic2.gif)  
图2 /ListUser.jsp

## 总结

通过Spring在Struts 2上实现控制反转是强烈推荐的做法，当然您也可以组合其它的实现（如Pico等）。