DIV CSS 佈局教程網

Buffalo 與 Spring 整合的難題:自製 BuffaloPlugIn 的實踐
編輯:AJAX基礎知識     

先說結論:Buffalo 對 Ajax 的處理能力相當值得期待,而它與 Spring 的整合也是一個亮點——只是這個亮點,用起來有些別扭。

問題出在哪裡

假設你用 Spring + Struts + Hibernate 搭一套輕量級 J2EE 架構。Spring 與 Struts 的整合有好幾種方式,其中最常見的是透過 Struts 的 PlugIn 機制,把 Spring 的 ContextLoader 掛上去:

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

這段設定想必很眼熟。問題就在這裡:Buffalo 支援 Spring 的方式,卻要求在 web.xml 裡另外配置:

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<servlet>
  <servlet-name>context</servlet-name>
  <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

上面這段是 Buffalo 與 Spring 整合的必要條件。但如果你的 Spring 與 Struts 已經用 PlugIn 方式整合(也就是由 Spring 來管理 Action),卻又要為了 Buffalo 在 web.xml 裡再配置一次 Spring 的東西,怎麼看都覺得彆扭。

另一個困擾:context 是怎麼取的

Buffalo 取得 WebApplicationContext 的方式是:

WebApplicationContextUtils.getWebApplicationContext(context);

也就是每次從 ServletContext 裡撈。但 ContextLoaderPlugIn 早就把 WebApplicationContext 的實例放在 ServletContext 裡了——同一份東西,兩套取用路徑,總讓人覺得有點浪費。

解法:寫一個 BuffaloPlugIn

於是我動手在 Buffalo 裡實作了一個 PlugIn,讓它能直接取用 Spring 放在 ServletContext 中的那份 WebApplicationContext,而不必依賴 WebApplicationContextUtils 重新取得。

程式碼寫得不夠規範,姑且湊合著看:

/**
 * @Descripted <B>Buffalo + Spring + Struts + Hibernate</B>
 *              <P></P>
 * @author meconsea
 * @date   2006-11-16
 * @Version 1.0Beta
 */
public class BuffaloPlugIn implements PlugIn {

    public static final Logger log = Logger.getLogger(BuffaloPlugIn.class);

    public static final String SERVLET_CONTEXT_PREFIX =
            ContextLoaderPlugIn.class.getName() + ".CONTEXT.";
    public static final String BUFFALO_CONTEXT_PREFIX =
            BuffaloPlugIn.class.getName() + ".CONTEXT.";

    private ModuleConfig moduleConfig;
    private ActionServlet actionServlet;

    // ... 其餘實作
}

這裡的設計意圖是透過兩個前綴常數來標識存放位置:沿用 ContextLoaderPlugIn 的命名空間前綴去取用 Spring 已經放好的 context,再以 Buffalo 自己的前綴管理屬於它的資源,避免兩邊互相覆蓋。

幾點省思

這段折騰背後其實反映了一個常見的整合困境:兩個框架各自對「誰擁有多少責任」有不同的假设。Spring 認為容器該由自己啟動,Struts 的 PlugIn 機制也是;而 Buffalo 作為第三方,只能假設容器已經在某處準備好,於是用了最保險也最消極的方式——重新問一次 ServletContext。

動手寫 PlugIn bridges 這個落差,代價是綁住了特定的整合方式(PlugIn 而非 ContextLoaderServlet)。若專案日後改用後者,這個 PlugIn 就失去意義。因此實務上更值得先確認的是:團隊究竟採用哪一種 Spring–Struts 整合方式,然後讓 Ajax 層去適應它,而不是反過來。

另外提醒一點:Logger 取得方式與 ModuleConfig 的注入時機,在不同 Struts 版本間曾有差異;升級版本時這類自製 PlugIn 往往是最容易出問題的一環,值得在每次升級後回歸測試一次。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved