- AspectJ支持五种通知注解:前置注解(Before)、后置通知(After)、返回通知(AfterRunning)、异常通知(AfterThrowing)、环绕通知(Around)
一、前置通知
//把这个类声明为一个切面:需要把该类放入IOC容器、在声明一个切面
@Aspect//声明一个切面
@Component//放入IOC容器
public class LoggingAspect {
//声明该方法是一个前置通知:在目标方法开始之前执行
@Before("execution(public int com.imooc.aop.impl.ArithmeticCalculator.add(int, int))")
public void beforeMethod(JoinPoint joinPoint){
String methodName=joinPoint.getSignature().getName();
List<Object> args=Arrays.asList(joinPoint.getArgs());
System.out.println("The method "+methodName+" begins "+args);
}
}
二、后置通知
- 在连接点完成之后执行的,即连接点返回结果或者抛出异常的时候,下面的后置通知记录了方法的终止
- 一个切面可以包含一个或多个通知
//后置通知:在目标方法执行后(无论是否发生异常),执行通知
//在后置通知中还不能访问目标方法执行的结果
@After("execution(* com.imooc.aop.impl.*.*(int, int))")
public void afterMethod(JoinPoint joinPoint){
String methodName=joinPoint.getSignature().getName();
System.out.println("The method "+methodName+" end ");
}
三、返回通知
/*
* 在方法正确执行后执行的代码
* 返回通知是可以访问到方法的返回值的
*/
@AfterReturning(value="execution(* com.imooc.aop.impl.*.*(int, int))",
returning="result")
public void afterReturntingMethod(JoinPoint joinPoint,Object result){
String methodName=joinPoint.getSignature().getName();
System.out.println("The method "+methodName+" end "+result);
}
四、异常通知
- 可以访问到方法出现的异常
- 可以访问到异常对象;且可以指定再出现特定异常时在执行通知代码
@AfterThrowing(value="execution(* com.imooc.aop.impl.*.*(int, int))",
throwing="ex")
//public void afterThrowingMethod(JoinPoint joinPoint,NullPointerException ex){
public void afterThrowingMethod(JoinPoint joinPoint,Exception ex){
String methodName=joinPoint.getSignature().getName();
System.out.println("The method "+methodName+" occurs excetion:"+ex);
}
五、环绕通知
/*
* 环绕通知:必须携带ProceedingJoinPoint类型参数
* 环绕通知类似于动态代理的全过程:ProceedingJoinPoint类型的参数可以决定是否执行目标方法
* 且环绕通知必须有返回值,返回值即为目标方法的返回值
*/
@Around("execution(* com.imooc.aop.impl.*.*(int, int))")
public Object aroundMethod(ProceedingJoinPoint pdb){
Object result=null;
String methodName=pdb.getSignature().getName();
try {
//前置通知
System.out.println("The method "+methodName+" begins "+Arrays.asList(pdb.getArgs()));
//执行目标方法
result=pdb.proceed();
//后置通知
System.out.println("The method "+methodName+" end "+result);
} catch (Throwable e) {
//异常通知
System.out.println("The method "+methodName+" occurs excetion:"+e);
throw new RuntimeException(e);
}
return result;
}