在 java企业开发一:struts2基础上进行集成spring3.
1.添加依赖:
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>${struts.version}</version>
</dependency>
注释:添加些依赖后会自动添加spring依赖.其中struts2-spring-plugin-x.x.x.jar里面有struts-plugin.xml,里面指明了struts.objectFactory为spring,
意思即为action交给spring管理,并且Action bean的作用域都是prototype.
另一方面该插件会按byName实现自动装配.所以要注意bean的name和在action加上的set方法.
2.在web.xml添加org.springframework.web.context.ContextLoaderListener(作用是初始化spring容器),此时也要相应指明spring容器文件放在那,也就是指是contextConfigLocation值.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3.在struts.xml配置action(注意action的class写全名)
<action name="/user/*" class="com.test.web.UserAction" method="{1}">
<result>/user/{1}.jsp</result>
</action>
.4.写服务层逻辑,在action注入依赖,也就是第一步提到的注释(set方法的名字要与注入的bean名字一致)
比如要注入userServiceImpl bean,但这个Action的属性是userService:
使用setter方法注入:
private UserService userService;
public void setUserServiceImpl(UserService userService) {
this.userService = userService;
}
或者在属性使用注解注入如:
@Resource(name="userServiceImpl")
private UserService userService;
5.测试集成
源代码:http://download.csdn.net/detail/xiejx618/6938167