开发者

Spring AOP misses something

开发者 https://www.devze.com 2023-01-16 15:16 出处:网络
I\'m just playing with AspectJ (1.6) with Spring (2.5), but it seems not to work in the proper way. I set up my \"beans.xml\" using:

I'm just playing with AspectJ (1.6) with Spring (2.5), but it seems not to work in the proper way. I set up my "beans.xml" using:

<aop:aspectj-autoproxy/>
<bean id="testBean1" class="apackage.MyClass">
<bean id="aopBean1" class="apacka开发者_如何学编程ge.AfterReturningExample"/>

with the correct namespaces set and some other beans with no importance. I use a simple bean to test advices:

package apackage;

        @Aspect
        public class MyClass {

            public MyClass()
            {

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

And this is the 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");
        }
    }

And finally this is the testing code (in a main method):

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

The output prints only:

returning from MyClass.testAspectJ()

The strange thing is that if I use for the pointcut:

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

the log shows the System.out.println of the AfterReturningExample class. What am I missing?


Solution found! First of all, MyClass is not an Aspect so doesn't need an @Aspect annotation. Second thing, MyClass must be an implementation of a given Interface (said MyClassInterface), and in the test code, I better use MyClassInterface bean = (MyClassInterface) ctx.getBean("testBean1");. I could use a class proxy, rather than an interface, only if in the beans.xml I'd added <aop:aspectj-autoproxy proxy-target-class="true"/> and a CGLIB lib in the classpath.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号