Struts 1.x 作為經典 MVC 框架廣泛應用,Spring 輕量級容器提供強大的 DI/AOP 能力。本文通過實例詳解如何利用 Spring 的 ActionSupport 類整合 Struts,實現業務層解耦。
在 struts-config.xml 中聲明插件:
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-INF/beans.xml"/>
</plug-in>
啟動時自動載入 Spring 配置,構建 WebApplicationContext。
public class SearchSubmit extends ActionSupport { // (1) 關鍵繼承
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
DynaActionForm searchForm = (DynaActionForm) form;
String cardno = (String) searchForm.get("cardno");
// (2) 獲取 Spring 容器
ApplicationContext ctx = getWebApplicationContext();
// (3) 從容器獲取業務 Bean
CreditcardService service = (CreditcardService) ctx.getBean("creditcardService");
CreditCard card = service.read(cardno.trim());
if (card == null) {
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("message.notfound"));
saveErrors(request, errors);
return mapping.findForward("failure");
}
request.setAttribute("creditcard", card);
return mapping.findForward("success");
}
}
| 維度 | 評價 | 說明 |
|---|---|---|
| 開發效率 | ⭐⭐⭐⭐⭐ | 最簡單,無額外配置,Action 直接獲取 Bean |
| 耦合度 | ⭐⭐ | Action 硬依賴 Spring API,難以單元測試,替換容器需改代碼 |
| AOP 支持 | ❌ | Action 不在 Spring 管理下,無法套用事務/日誌切面 |
| 生命周期 | ⚠️ | Action 由 Struts 實例化(單例/多例),非 Spring 管控 |
getWebApplicationContext() 獲取代理RequestProcessor 讓 Spring 管理 Action 實例,實現完整 DI/AOP<bean id="creditcardService" class="com.infotek.Creditcard.business.CreditcardServiceImpl">
<property name="dao" ref="creditcardDao"/>
</bean>
<bean id="creditcardDao" class="com.infotek.Creditcard.dao.CreditcardDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
ActionSupport 方案是「以最小代價引入 Spring DI」的戰術選擇,適合存量項目快速受益。但長期看,Action 應退化為薄薄的 Web 適配層,核心業務邏輯下沉至 Spring 管理的 Service 層,並逐步向 Spring MVC 或現代框架演進。