Spring框架基于注解的AOP之各种通知的使用与环绕通知实现详解

发布时间:

这篇文章主要介绍了Spring框架基于注解的AOP之各种通知的使用及其环绕通知,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧!

Spring框架基于注解的AOP之各种通知的使用与环绕通知实现详解

一、基于注解的AOP之各种通知的使用

1.在切面中,需要通过指定的注解将方法标识为通知方法

@Before:前置通知,在目标对象方法执行之前执行

@After:后置通知,在目标对象方法的finally子句中执行

@AfterReturning:返回通知,在目标对象方法返回值之后执行

@AfterThrowing:异常通知,在目标对象方法的catch子句中执行

声明重用写入点表达式

@Pointcut("execution(* com.tian.spring.aop.annotation.CalculatorImpl.*(..))")
public void pointCut() {
}

①前置通知

//@Before("execution(public int com.tian.spring.aop.annotation.CalculatorImpl.add(int,int))")
//@Before("execution(* com.tian.spring.aop.annotation.*.*(..))")
@Before("pointCut()")
public void beforeAdviceMethod(JoinPoint joinPoint) {
//获取连接点所对应方法的签名信息
Signature signature = joinPoint.getSignature();
//获取连接点所对应方法的参数
Object[] args = joinPoint.getArgs();
System.out.println("LoggerAspect,方法:" + signature.getName() + ",参数" + Arrays.toString(args));
}

②后置通知

@After("pointCut()")
public void afterAdviceMethod(JoinPoint joinPoint) {
//获取连接点所对应方法的签名信息
Signature signature = joinPoint.getSignature();
System.out.println("LoggerAspect,方法:" + signature.getName() + ",执行完毕");
}

③返回通知

/**
 *在返回通知中若要获取目标对象方法的返回值
 *只需要通过@AfterReturning注解的returnings属性
 * 就可以将通知方法的某个参数指定为接收目标对象方法的返回值的参数
 */
@AfterReturning(value = "pointCut()",returning = "result")
public void afterReturningAdviceMethod(JoinPoint joinPoint,Object result) {
//获取连接点所对应方法的签名信息
Signature signature = joinPoint.getSignature();
System.out.println("LoggerAspect,方法" + signature.getName() + ",结果:" + result);
}

④异常通知

/**
 *在异常通知中若要获取目标对象方法的异常
 *只需要通过@AfterThrowing注解的throwing属性
 * 就可以将通知方法的某个参数指定为接收目标对象方法的异常的参数
 */
@AfterThrowing(value = "pointCut()",throwing = "ex")
public void afterThrowingAdvice(JoinPoint joinPoint,Throwable ex) {
Signature signature = joinPoint.getSignature();
System.out.println("LoggerAspect,方法:" + signature.getName() + ",异常:" + ex);
}

二、基于注解的AOP之环绕通知

环绕通知:

通过@Around,然后通过切入点表达式定位到连接点,然后在环绕通知的方法中需要传进去一个参数,叫做ProceedingJoinPoint类型的参数,然后通过这个参数中的一个方法,proceed()就可以来表示目标方法的执行了,然后我们就可以在方法执行的过程中,添加额外的操作了

环绕通知的方法的返回值,一定要和目标对象方法的返回值一致

 @Around("pointCut()")
public Object aroundAdviceMethode(ProceedingJoinPoint joinPoint) {
Object result = null;
try {
System.out.println("环绕通知-->前置通知");
//表示目标对象方法的执行
result = joinPoint.proceed();
System.out.println("环绕通知-->返回通知");
} catch (Throwable e) {
e.printStackTrace();
System.out.println("环绕通知-->异常通知");
} finally {
System.out.println("环绕通知-->后置通知");
}
return result;
}

测试类:

@Test
public void testAOPByAnnotation() {
ApplicationContext ioc = new ClassPathXmlApplicationContext("aop-annotation.xml");
Calculator calculator = ioc.getBean(Calculator.class);
calculator.div(10,1);
}