首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring 整合 Struts 三大招式:從 ActionSupport 到動態代理的最佳實踐

     編輯:Java 相關知識

Struts 1.x 時代,將 Action 納管給 Spring IoC 容器可享受依賴注入、AOP 攔截器等紅利。本文對比三種整合方案,推薦「動作委派」模式為最佳實踐。

前置條件:ContextLoaderPlugIn 載入 Spring 容器

<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
    <set-property property="contextConfigLocation" value="/WEB-INF/beans.xml"/>
</plug-in>

招式一:繼承 Spring ActionSupport(入門級,強耦合)

public class SearchSubmit extends ActionSupport { // 繼承 Spring 基類
    public ActionForward execute(...) {
        ApplicationContext ctx = getWebApplicationContext(); // 取容器
        BookService svc = (BookService) ctx.getBean("bookService"); // 手動查找
        ...
    }
}
  • ✅ 簡單直觀
  • ❌ Action 強依賴 Spring API,移植困難
  • ❌ Action 不在 Spring 管理下,無法享受 AOP、生命周期回調

招式二:覆蓋 RequestProcessor(巧妙解耦,擴展性受限)

<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/>
<bean name="/searchSubmit" class="ca.nexcel.books.actions.SearchSubmit">
    <property name="bookService" ref="bookService"/>
</bean>
public class SearchSubmit extends Action { // 繼承 Struts 原生 Action
    private BookService bookService;
    public void setBookService(BookService svc) { this.bookService = svc; } // Setter 注入
    ...
}
  • ✅ Action 無 Spring 依賴,純 POJO
  • ✅ 支援 Setter 注入、單例/原型模式切換
  • ❌ 若專案自定義 RequestProcessor,需手動整合 DelegatingRequestProcessor
  • ❌ Struts 未來可能以 Command 取代 RequestProcessor,壽命存疑

招式三:DelegatingActionProxy 動作委派(最佳實踐,完全解耦)

<action path="/searchSubmit"
        type="org.springframework.web.struts.DelegatingActionProxy" />
<bean name="/searchSubmit" class="ca.nexcel.books.actions.SearchSubmit">
    <property name="bookService" ref="bookService"/>
</bean>
  • ✅ struts-config 僅聲明代理類,Action 完全不感知 Spring
  • ✅ Action 由 Spring 完整管理:注入、AOP、init-method/destroy-method、原型模式
  • ✅ 不受 RequestProcessor 變更影響,長期穩定

實戰:AOP 攔截器為 Action 加上日誌切面

// 1. 定義攔截器
public class LoggingInterceptor implements MethodBeforeAdvice {
    public void before(Method m, Object[] args, Object target) {
        System.out.println("Logging before: " + m.getName());
    }
}
// 2. Spring 配置自動代理
<bean name="logger" class="ca.nexcel.books.interceptors.LoggingInterceptor"/>
<bean name="loggingAutoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
    <property name="beanNames">
        <list><value>/searchSubmit</value></list>
    </property>
    <property name="interceptorNames">
        <list><value>logger</value></list>
    </property>
</bean>

無需修改 Action 代碼,即可橫切織入日誌、事務、效能監控等關注點。

總結對比

方案耦合度AOP 支援生命周期管理推薦指數
ActionSupport高(依賴 Spring API)無無⭐
DelegatingRequestProcessor低有有⭐⭐⭐
DelegatingActionProxy零有完整⭐⭐⭐⭐⭐

以 DelegatingActionProxy 為核心的「動作委派」模式,讓 Struts 專注於 Web 層調度,Spring 專注於業務對象管理與切面織入,是經典架構整合的教科書級範例。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved