1.@AfterReturning返回通知
2.@AfterThrowing 异常通知
@Aspect
@Component
public class Log {
/**
* 返回通知:在方法正常结束后返回的通知。
* 返回通知可以访问到目标方法的返回值
*
*/
@AfterReturning(value = "execution(int com.lishenhuan.aop.impl.ArithmeticCalculator.*(int, int))"
,returning="result")
public void afterReturning(JoinPoint joinPoint,Object result) {
String mathodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method " + mathodName + " end with " + result);
}
/**
* 异常通知:在目标方法出现异常时,可以访问到异常对象。
* 并且可以指定只有在出现某种特定异常的时候再执行通知代码。
*
*/
@AfterThrowing(value = "execution(int com.lishenhuan.aop.impl.ArithmeticCalculator.*(int, int))"
,throwing="ex")
public void afterThrowing(JoinPoint joinPoint,Exception ex) {
String mathodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method " + mathodName + " occurs exception: " + ex);
}
}
3.环绕通知。
•环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点.
•对于环绕通知来说, 连接点的参数类型必须是 ProceedingJoinPoint . 它是 JoinPoint 的子接口,
允许控制何时执行, 是否执行连接点.
•在环绕通知中需要明确调用 ProceedingJoinPoint 的 proceed() 方法来执行被代理的方法.
如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行.
•注意: 环绕通知的方法需要返回目标方法执行之后的结果, 即调用 joinPoint.proceed(); 的返回值,
否则会出现空指针异常
/**
*环绕通知:必须携带ProceedingJoinPoint类型的参数。
*环绕通知类似于动态代理的全过程:ProceedingJoinPoint类型的参数。决定目标方法是否执行
*环绕通知必须有返回值,返回值即为目标方法的返回值。
*/
@Around("execution(int com.lishenhuan.aop.impl.ArithmeticCalculator.*(int, int))")
public Object round(ProceedingJoinPoint pdj) {
Object result = null;
//执行目标方法
try {
result = pdj.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
return result;
}