【问题标题】:Spring AOP misses somethingSpring AOP 遗漏了一些东西
【发布时间】:2010-09-19 20:57:45
【问题描述】:

我只是在使用 AspectJ (1.6) 和 Spring (2.5),但它似乎不能以正确的方式工作。 我使用以下方法设置了“beans.xml”:

<aop:aspectj-autoproxy/>
<bean id="testBean1" class="apackage.MyClass">
<bean id="aopBean1" class="apackage.AfterReturningExample"/>

设置了正确的命名空间和其他一些不重要的 bean。 我使用一个简单的 bean 来测试建议:

package apackage;

        @Aspect
        public class MyClass {

            public MyClass()
            {

            }
                public Boolean testAspectJ()
                {
                        System.out.println("returning from MyClass.testAspectJ()");
                        return false;
                }
        }

这是 aop bean:

package apackage;    
@Aspect 
    public class AfterReturningExample {
        public AfterReturningExample(){}
        @AfterReturning("execution(* apackage.MyClass.*(..))")
        public void test() throws Exception{

            System.err.println("\n\n####  After Returning MyClass.testAspectJ()\n\n");
        }
    }

最后这是测试代码(在 main 方法中):

ApplicationContext ctx = new ClassPathXmlApplicationContext("apackage/beans.xml"); 
MyClass bean = (MyClass) ctx.getBean("testBean1"); 
bean.testAspectJ();

只打印输出:

returning from MyClass.testAspectJ()

奇怪的是,如果我使用切入点:

"execution(public * *(..))"

日志显示了 AfterReturningExample 类的 System.out.println。 我错过了什么?

【问题讨论】:

    标签: spring spring-aop


    【解决方案1】:

    找到解决方案! 首先,MyClass 不是 Aspect,因此不需要 @Aspect 注释。 第二件事,MyClass 必须是给定接口的实现(即MyClassInterface),在测试代码中,我最好使用MyClassInterface bean = (MyClassInterface) ctx.getBean("testBean1");。 我可以使用类代理而不是接口,前提是在 beans.xml 中添加了&lt;aop:aspectj-autoproxy proxy-target-class="true"/&gt; 和类路径中的 CGLIB 库。

    【讨论】:

      猜你喜欢
      • 2013-07-12
      • 1970-01-01
      • 2021-04-25
      • 2011-05-14
      • 2019-05-17
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多