0

我目前正在使用 XML 功能测试 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 消息。我的代码有什么问题?

4

1 回答 1

0

使用proxy-target-classin<aop:config>强制使用 CGLIB 代理。

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

如果您在客户端使用代理MainClass,那么您需要引用代理来调用hello()而不是this. 请参考这篇写得很好的关于 AOP 代理的文档,以了解我的目标。

于 2013-07-18T05:27:32.590 回答