此文章的代碼是在另一篇有關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等。