一. 知识储备
1.1 返回通知
在LoggingAspect.java中添加以下方法,就是返回通知的语法:
/**
* 返回通知:在目标方法正常返回后执行,可以获取到方法的返回值
* 通过returning="变量名"来接收方法的返回值,
* returning指定的名字必须要与方法中用于接收返回值的形参名一致
*/
@AfterReturning(value="execution(* com.atguigu.spring.aop.aspectJ.*.*(..))", returning="result")
public void afterReturningMethod(JoinPoint joinPoint, Object result) {
String methodName = joinPoint.getSignature().getName();
System.out.println("LoggingAspect==> The method " + methodName + "ends with: " + result);
}
1.2 异常通知
在LoggingAspect.java中添加以下方法,就是异常通知的语法:
/**
* 异常通知:在目标方法抛出异常后执行
* 通过throwing="变量名"来接收异常信息,throwing指定的名字必须要与方法中用于接收异常的形参名一致
*
* 还可以通过方法中接收异常的形参类型 来 指定抛出什么异常才执行异常通知
*/
@AfterThrowing(value="execution(* com.atguigu.spring.aop.aspectJ.*.*(..))", throwing="ex")
public void afterThrowingMethod(JoinPoint joinPoint, Exception ex) {
//获取方法名
String methodName = joinPoint.getSignature().getName();
System.out.println("LoggingAspect==> The method " + methodName + " occurs Exception: " + ex);
}
在LoggingAspect.java中添加以下方法,就是环绕通知的语法:
/**
* 环绕通知:环绕着目标方法执行,可以理解为前置 后置 返回 异常的结合,类似于动态代理的整个过程
*
*/
@Around(value="execution(* com.atguigu.spring.aop.aspectJ.*.*(..))")
public Object aroundMethod(ProceedingJoinPoint pjp) {
try {
//前置
//调用目标方法
Object result = pjp.proceed();
//返回
return result;
} catch (Throwable e) {
// TODO Auto-generated catch block
//异常
e.printStackTrace();
}finally {
//后置
}
return null;
}