2013年1月15日 星期二

Integrate Spring AOP with Struts2 Action

若是要使用Spring AOP來攔截Struts2 Action,首先當然要讓Spring管理所有的Action object,細節可以參考:Struts2 Convention Plugin with Spring Plugin

接下來可能會發生兩個問題:
  1. java.lang.NoSuchMethodException:原因是一般Action method不太會特別製作interface,預設Spring AOP會以interfaces為準,此時AOP proxy就不會有Action method,那麼就會發生此問題。
  2. Missing parameters:若Action scope被設定為prototype就會有此問題,因為每個method call都會讓Spring AOP proxy object重新new Action object,這樣之前呼叫過setter的parameter就會遺失。
解決方法:
  1. 修改@Scope參數
  2. 代碼:
    import org.springframework.context.annotation.Scope;
    import org.springframework.context.annotation.ScopedProxyMode;
    import org.springframework.web.context.WebApplicationContext;

    @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
  3. 在web.xml中添加org.springframework.web.context.request.RequestContextListener
  4. web.xml
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
讓Action object的scope定在request,並且強制Spring使用CGLIB產生proxy,這樣就能順利在Struts2 Action上使用Spring AOP。