整合 Spring 和 Strust2

本文详细介绍了如何在Struts2中整合Spring的IoC支持,包括配置步骤、Spring监听器、对象注册以及Struts配置调整等核心内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自:http://hpfyeah.iteye.com/blog/57066

在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. <struts>  
  2.     <constant name="struts.objectFactory" value="spring" />  
  3. </struts>  

3)配置Spring监听器

web.xml
  1. <listener>  
  2.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  3. </listener>  

通过Spring配置来注册对象

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

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

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

4)修改你的Struts配置文件

struts.xml
  1. <!DOCTYPE struts PUBLIC      
  2.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"      
  3.     "http://struts.apache.org/dtds/struts-2.0.dtd">     
  4. <struts>     
  5.     <include file="struts-default.xml"/>     
  6.     <package name="default" extends="struts-default">     
  7.         <action name="pureStruts" class="hello">
  8.             <result>hello.jsp</result>     
  9.         </action>  
  10.         <action name="springStruts" class="hello">      
  11.             <result>hello.jsp</result>     
  12.         </action>     
  13. </struts>  

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

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

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

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

struts.properties
  1. struts.objectFactory.spring.useClassCache = false 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值