我们可以通过对比前置通知和后置通知,来学习后置通知。下面是一个切面类,里面有前置和后置通知两种。
//把这个类声明为一个切面
@Aspect
@Component
public class LoggingAspect {
@Before("execution(public int spring.impl.AtithmeticCaculator.*(int, int))")
public void beforeMethod(JoinPoint joinPoint){
String methodName=joinPoint.getSignature().getName();
List<Object> args=(List) Arrays.asList(joinPoint.getArgs());
System.out.println("======================================="+methodName+"方法开始"+"参数为 "+args);
}
//后置通知,在方法执行后执行通知,无论是否发生异常
//注意,在后置通知中不能访问目标方法的访问结果,执行结果要在返回通知中访问
@After("execution(public int spring.impl.AtithmeticCaculator.*(int, int))")
public void afterMethod(JoinPoint joinPoint){
String methodName=joinPoint.getSignature().getName();
System.out.println("the method "+methodName+" end");
}
}
注意备注里的话,返回通知才能调用结果,后置通知是不能和结果挂勾的。