现在的位置: 首页 > 综合 > 正文

Struts2.x和Spring3.x集成

2013年08月12日 ⁄ 综合 ⁄ 共 1549字 ⁄ 字号 评论关闭

官方文struts-spring Plugin文档:
http://struts.apache.org/release/2.3.x/docs/spring-plugin.html
官方文Struts2+Spring2+JPA+AJAX文档:
http://struts.apache.org/release/2.3.x/docs/struts-2-spring-2-jpa-ajax.html

集成步骤:
1.引入struts2-spring-plugin-x-x-x.jar插件;
2.在web.xml中添加Spring listener;
3.在web.xml中加入多个applicationContext.xml文件的配置;
4.编写你的Actions和Services
5.在struts.xml配置action,在applicationContext.xml配置Bean;

关键点:
1.通过struts2-spring-plugin-x-x-x.jar插件完成,所以先要在程序中引入这个包;

2.在web.xml中配置Spring listener:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

3.如果有多个Spring的applicationContext配置文件(通常一个应用程序不止一个):

在web.xml中加入下面片断:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>
</context-param>

4.把Actions交给Spring容器管理

注:这项可以不用添加到struts.xml文件!
由于struts2-spring-plugin-x-x-x.jar包中的struts-plugin.xml已经配置了由Spring容器来管理Actions,所以如下配置可以不用添加:

<constant name="struts.objectFactory" value="spring" />

5.理解Struts2的autoWire(自动装配)

注:这项可以不用添加到struts.xml文件!
struts.objectFactory.spring.autoWire默认值为name:

<constant name="struts.objectFactory.spring.autoWire" value="name" />

value属性的值:
name(默认,推荐): Spring根据Action中属性名称去匹配(matching)Spring容器中有相同名称的Bean;
type: Spring根据ction中属性名称的类型在Spring容器中去查找(looking for)与之相同的Bean;
auto: Spring尝试自动侦测最合适的方法去装配action;
constructor: Spring自动装配构造函数参数对应的Bean;

注:如果value值为type,注定一个class在Spring容器中只能注册一次.

6.从Spring实例化Actions
官方推荐让Spring容器去管理Action实例,在struts.xml中使用Spring容器管理的Bean作为class属性值,
这样也可以避免你维护struts.xml和applicationContext.xml两处Action类的配置.

抱歉!评论已关闭.