AOP
AOP的入门案例:
AOP的工作流程
SpringAop的本质是:代理模式
AOP的切入点表达式
重用切入点表达式:
①声明
@Pointcut(“execution( com.atguigu.aop.annotation..*(..))”)
public void pointCut(){}
②在同一个切面中使用
@Before(“pointCut()”) public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
String args = Arrays.toString(joinPoint.getArgs());
System.out.println(“Logger–>前置通知,方法名:”+methodName+”,参数:”+args);
}
③在不同切面中使用
@Before(“com.atguigu.aop.CommonPointCut.pointCut()”) public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
String args = Arrays.toString(joinPoint.getArgs());
System.out.println(“Logger–>前置通知,方法名:”+methodName+”,参数:”+args);
}
获取通知的相关信息
①获取连接点信息 获取连接点信息可以在通知方法的参数位置设置JoinPoint类型的形参
@Before(“execution(public int com.atguigu.aop.annotation.CalculatorImpl.*(..))”)
public void beforeMethod(JoinPoint joinPoint){
//获取连接点的签名信息
String methodName = joinPoint.getSignature().getName();
//获取目标方法到的实参信息
String args = Arrays.toString(joinPoint.getArgs());
System.out.println(“Logger–>前置通知,方法名:”+methodName+”,参数:”+args);
}
②获取目标方法的返回值
@AfterReturning中的属性returning,用来将通知方法的某个形参,接收目标方法的返回值
@AfterReturning(value = “execution( com.atguigu.aop.annotation.CalculatorImpl. (..))”, returning = “result”)
public void afterReturningMethod(JoinPoint joinPoint, Object result){
String methodName = joinPoint.getSignature().getName();
System.out.println(“Logger–>返回通知,方法名:”+methodName+”,结果:”+result);
}
③获取目标方法的异常
@AfterThrowing中的属性throwing,用来将通知方法的某个形参,接收目标方法的异常
@AfterThrowing(value = “execution( com.atguigu.aop.annotation.CalculatorImpl. (..))”, throwing = “ex”)
public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
String methodName = joinPoint.getSignature().getName();
System.out.println(“Logger–>异常通知,方法名:”+methodName+”,异常:”+ex);
}
环绕通知
@Around(“execution( com.atguigu.aop.annotation.CalculatorImpl.(..))”)
public Object aroundMethod(ProceedingJoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
String args = Arrays.toString(joinPoint.getArgs());
Object result = null;
try {
System.out.println(“环绕通知–>目标对象方法执行之前”); //目标方法的执行,目标方法的返回值一定要返回给外界调用者
result = joinPoint.proceed(); System.out.println(“环绕通知–>目标对象方法返回值之后”);
} catch (Throwable throwable) { throwable.printStackTrace(); System.out.println(“环绕通知–>目标对象方法出现异常时”);
} finally {
System.out.println(“环绕通知–>目标对象方法执行完毕”);
} return result;
}
Original: https://www.cnblogs.com/Cxxxd/p/16705046.html
Author: Cxxxd
Title: AOP
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/713405/
转载文章受原作者版权保护。转载请注明原作者出处!