2013-07-17 28 views
0

我目前正在使用XML功能測試Spring的AOP,但我無法使其工作。使用XML的Java Spring AOP不起作用

編輯: 只有當方法從類的構造函數調用時纔會出現問題。

我的applicationContext.xml:

<beans xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"> 
    <aop:aspectj-autoproxy/> 
    <bean id="aopClass" class="hu.viper.aoptest.AopClass"/> 
    <bean id="mainClass" class="hu.viper.aoptest.MainClass"/> 
    <aop:config> 
    <aop:aspect ref="aopClass"> 
     <aop:pointcut id="pointCutBefore" expression="execution(* hu.viper.aoptest.MainClass.hello(..))"/> 
     <aop:before method="writeAOP" pointcut-ref="pointCutBefore"/> 
    </aop:aspect> 
    </aop:config> 
</beans> 

我MainClass.java:

package hu.viper.aoptest; 

public class MainClass { 

    public MainClass() { 
     this.hello(); 
    } 

    public void hello() { 
     System.out.println("HELLO WORLD"); 
    } 
} 

我AopClass.java:

package hu.viper.aoptest; 

import org.aspectj.lang.JoinPoint; 

public class AopClass { 
    public void writeAOP(JoinPoint joinPoint) { 
     System.out.println("This is the AOP message!"); 
    } 
} 

它建立完美,當我運行它,它在NetBeans的GlassFish輸出中兩次打印「HELLO WORLD」(我不知道爲什麼會出現兩次),但沒有AOP消息。我的代碼有什麼問題?

+0

我會檢查'CGLib'是否在類路徑中?它應該在那裏,因爲你嘗試代理一個類(而不是一個接口)。 – LaurentG

+0

CGLib在類路徑中。 – Kompi

回答

0

使用proxy-target-class<aop:config>強制使用CGLIB代理。

<aop:config proxy-target-class="true"> 
    ....... 
</aop:config> 

如果您正在使用代理服務器爲客戶端MainClass,那麼你就需要參考的代理來調用hello(),而不是this。請參閱this nicely written doc about AOP Proxies瞭解我的目標。

+0

仍然是同樣的問題:( – Kompi

+1

@kompi)對於測試,你可以直接從另一個方法調用hello()而不是MainClass中的構造函數,我不認爲它是通過構造函數調用時被代理的,事實上,如果它是代理的,那麼你必須使用代理來調用hello()而不是此運算符。 – dmahapatro

+0

當不通過構造函數調用時,它工作,謝謝。 – Kompi