【发布时间】:2018-01-24 17:58:23
【问题描述】:
我在学习 AOP 时遇到了一个场景。
所有的类都在包com.spring中
而Pointcut 定义了@AfterReturning 类型的Advice 对于任何类的包com.spring 中的任何方法,带有任意数量的参数。
spring.xml定义明确,在我的类路径中并且提供的代码正在运行
所以我的问题是,Aspects 类的这个建议不应该无限运行,因为它本身满足 Pointcut 定义吗?
这是我的方面类
package com.spring;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class Aspects {
@AfterReturning(pointcut = "execution(* com.spring.*.*(..))", returning= "res")
public void logAfterExecutionAdvice(int res){
System.out.print("Result in advice: "+res);
System.out.print(" In After Advice ");
}
}
我的加法器类
package com.spring;
public class Adder {
private int a;
private int b;
public int add(int a,int b){
return (a+b);
}
/**
* @return the a
*/
public int getA() {
return a;
}
/**
* @param a the a to set
*/
public void setA(int a) {
this.a = a;
}
/**
* @return the b
*/
public int getB() {
return b;
}
/**
* @param b the b to set
*/
public void setB(int b) {
this.b = b;
}
}
还有我的主类
package com.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
Adder adder=(Adder)ctx.getBean("adder");
System.out.print("Result=" + adder.add(2,3));
}
}
我得到的输出是 Result in advice: 5 In After Advice Result=5
【问题讨论】:
-
不,因为你的方面方法执行,但实际上并没有返回任何东西。
-
这是因为通知仅在 spring bean 上调用该方法时执行,在您的情况下
Adderbean 由 spring 维护,因此它仅适用于该 bean 的方法。 -
是不是@Aspect注解类中的所有方法都被切入点表达式排除在外?
-
@ShabbirEssaji 没错!!
-
如果你绝对想从其他切面中截取切面,你需要配置你的应用程序使用AspectJ而不是Spring AOP。那么就没有问题了。
标签: java spring aop aspectj spring-aop