Struts2整合Spring

此文章的代码是在另一篇有关Struts2文章代码的基础上完成的,请参考Struts项目实例

在引入Spring之前,如果我们的ActionSupport需要引用一些业务类,如下所示:

private UserService userService = new UserServiceImpl();
上面的代码把UserAction class和UserServiceImpl class的依赖关系写死了,这种设计很不友好,体现在下面两个方面。
  • 如果我需要UserService的另一个实现类替代UserServiceImpl,那我就需要找到并修改所有的依赖代码。
  • 没有UserServiceImpl我就无法测试UserAction类。我不能在编写测试用例时使用UserServiceImpl的子实现类来隔离UserAction,因为UserServiceImpl的使用是硬编码的。

Spring提供了一种机制,通过在运行时注入它们来管理依赖性。Struts 2 ActionSupport类——就像任何其他Java类一样——可以通过Spring框架注入依赖对象。因此,我没有使用上面的代码,而是在UserAction中有这个语句。

Spring提供了一种机制,通过运行时注入他们来管理依赖类。Struts 2 ActionSupport类就像其他的Java类一样,可以通过Spring框架注入依赖对象。因此,我没有使用上面的代码,而是在UserAction中有这个语句

//private UserService userService = new UserServiceImpl();
private UserService userService;
下面是整合Spring的需要的步骤:

1. 在pom.xml添加struts2-spring-plugin依赖包

Struts 2 Spring插件的当前版本(2.5.14.1)对Spring 4.1.9有传递依赖关系。如果您想要使用最新版本的Spring,那么您应该为Struts 2 Spring插件排除您的pom中的传递依赖项。然后声明依赖节点到Spring jar文件的当前最新版本版本。

<dependency>
	<groupId>org.apache.struts</groupId>
	<artifactId>struts2-spring-plugin</artifactId>
	<version>${struts2.version}</version>
</dependency>
2. 编写UserAction Class,不要再用硬编码依赖。同时必须为依赖对象添加set方法。
//private UserService userService = new UserServiceImpl();
private UserService userService;

public void setUserService(UserService userService) {
    this.userService = userService;
}

Spring会在运行时使用这个set方法为UserAction类提供一个UserService类型的实例。 will use that set method to provide

3. 在web.xml添加Spring监听

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

在应用被Servle容器起来的时候上面的代码会激活Spring框架。Spring默认情况下会到WEB-INF下面去找名字为applicationContext.xml的文件。

4. WEB-INF添加Spring配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">

	<bean id="userService" class="angelia.struts.service.UserServiceImpl" />

</beans>

使用上面的方法,Struts 2框架仍然需要管理ActionSupport类的创建。如果想Spring管理ActionSupport类的创建,可以通过applicationContext.xml文件的配置实现。

5. 有Spring管理ActionSupport Class的Spring配置

<bean id="userService" class="angelia.struts.service.UserServiceImpl" />
    
<bean id="userAction" class="angelia.struts.action.UserAction" scope="prototype">
        <property name="userService" ref="userService" />
</bean>
6. Spring管理ActionSupport类的Struts配置
<action name="loginInput" class="userAction" method="input">
	<result name="input">/newlogin.jsp</result>
</action>
		
<action name="login" class="userAction" method="execute">
	<result name="success">/index.jsp</result>
	<result name="input">/newlogin.jsp</result>
</action>

总结:

这篇文章大概讲了如何使用Struts2的Spring插件来集成Spring和Struts。通过使用Struts2的Spring插件,我们可以通过Spring来管理ActionSupport依赖的类。当然,Spring还有很多其他优势,比如AOP, Spring JDBC等。


猜你喜欢

转载自blog.csdn.net/u014010512/article/details/80937777