当前位置:   article > 正文

Spring知识整理(六)Spring之AOP的前置通知,后置通知,返回通知,异常通知,环绕通知_aop前置通知推送值到方法入参

aop前置通知推送值到方法入参

1.(AspectJ

 

AspectJJava 社区里最完整最流行的 AOP 框架.

Spring2.0以上版本, 可以使用基于 AspectJ注解或基于 XML 配置的 AOP

要在 Spring 应用中使用 AspectJ注解, 必须在 classpath下包含 AspectJ类库: aopalliance.jaraspectj.weaver.jar spring-aspects.jar

aop Schema 添加到 <beans> 根元素中.

Spring IOC 容器中启用 AspectJ注解支持, 只要Bean 配置文件中定义一个空的 XML 元素 <aop:aspectj-autoproxy>

SpringIOC 容器侦测到 Bean 配置文件中的 <aop:aspectj-autoproxy> 元素时, 会自动为与 AspectJ切面匹配的 Bean 创建代理.

要在 Spring 中声明 AspectJ切面, 只需要在 IOC 容器中将切面声明为 Bean 实例. 当在 Spring IOC 容器中初始化 AspectJ切面之后, Spring IOC 容器就会为那些与 AspectJ切面相匹配的 Bean 创建代理.

AspectJ注解中, 切面只是一个带有 @Aspect 注解的 Java .

通知是标注有某种注解的简单的 Java 方法.

AspectJ支持 5 种类型的通知注解:

@Before: 前置通知, 在方法执行之前执行

@After: 后置通知, 在方法执行之后执行

@AfterRunning: 返回通知, 在方法返回结果之后执行

@AfterThrowing: 异常通知, 在方法抛出异常之后

@Around: 环绕通知, 围绕着方法执行

1.1(前置通知)

 

前置通知:在方法执行之前执行的通知

前置通知使用 @Before 注解, 并将切入点表达式的值作为注解值.

可以在通知方法中声明一个类型为 JoinPoint的参数. 然后就能访问链接细节.

1.2(后置通知)

 

后置通知是在连接点完成之后执行的, 即连接点返回结果或者抛出异常的时候, 下面的后置通知记录了方法的终止.

一个切面可以包括一个或者多个通知.使用@After注解

1.3(返回通知)

 

无论连接点是正常返回还是抛出异常, 后置通知都会执行. 如果只想在连接点返回的时候做记录, 应使用返回通知代替后置通知.

在返回通知中, 只要将 returning属性添加到 @AfterReturning注解中, 就可以访问连接点的返回值. 该属性的值即为用来传入返回值的参数名称.

必须在通知方法的签名中添加一个同名参数. 在运行时, Spring AOP 会通过这个参数传递返回值.

 

1.4(异常通知)

 

只在连接点抛出异常时才执行异常通知

throwing 属性添加到 @AfterThrowing注解中, 也可以访问连接点抛出的异常. Throwable是所有错误和异常类的超类. 所以在异常通知方法可以捕获到任何错误和异常.

如果只对某种特殊的异常类型感兴趣, 可以将参数声明为其他异常的参数类型. 然后通知就只在抛出这个类型及其子类的异常时才被执行.

 

1.5(环绕通知(类似于动态代理))

 

环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点.

对于环绕通知来说, 连接点的参数类型必须是 ProceedingJoinPoint . 它是 JoinPoint的子接口, 允许控制何时执行, 是否执行连接点.

在环绕通知中需要明确调用 ProceedingJoinPointproceed() 方法来执行被代理的方法. 如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行.

注意: 环绕通知的方法需要返回目标方法执行之后的结果, 即调用 joinPoint.proceed(); 的返回值, 否则会出现空指针异常

 

2.(代码说明)

 

2.1(目标方法所在的bean)

 

  1. package com.spring.aop;
  2. public interface ArithmeticCalculator {
  3. int add(int i, int j);
  4. int sub(int i, int j);
  5. int mul(int i, int j);
  6. int div(int i, int j);
  7. }
 
  1. package com.spring.aop;
  2. import org.springframework.stereotype.Component;
  3. @Component("arithmeticCalculator")
  4. public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
  5. @Override
  6. public int add(int i, int j) {
  7. int result = i + j;
  8. return result;
  9. }
  10. @Override
  11. public int sub(int i, int j) {
  12. int result = i - j;
  13. return result;
  14. }
  15. @Override
  16. public int mul(int i, int j) {
  17. int result = i * j;
  18. return result;
  19. }
  20. @Override
  21. public int div(int i, int j) {
  22. int result = i / j;
  23. return result;
  24. }
  25. }

 

2.2(切面)

 

  1. package com.spring.aop;
  2. import java.util.Arrays;
  3. import org.aspectj.lang.JoinPoint;
  4. import org.aspectj.lang.annotation.*;
  5. import org.springframework.stereotype.Component;
  6. /**
  7. * AOP 的配置顺序
  8. * 1. 加入 jar 包
  9. * com.springsource.net.sf.cglib-2.2.0.jar
  10. * com.springsource.org.aopalliance-1.0.0.jar
  11. * com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
  12. * spring-aspects-4.0.0.RELEASE.jar
  13. *
  14. * 2. 在 Spring 的配置文件中加入 aop 的命名空间。
  15. *
  16. * 3. 基于注解的方式来使用 AOP
  17. * 3.1 在配置文件中配置自动扫描的包: <context:component-scan base-package="com.spring.aop"></context:component-scan>
  18. * 3.2 加入使 AspjectJ 注解起作用的配置: <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  19. * 为匹配的类自动生成动态代理对象.
  20. *
  21. * 4. 编写切面类:
  22. * 4.1 一个一般的 Java 类
  23. * 4.2 在其中添加要额外实现的功能.
  24. *
  25. * 5. 配置切面
  26. * 5.1 切面必须是 IOC 中的 bean: 实际添加了 @Component 注解
  27. * 5.2 声明是一个切面: 添加 @Aspect
  28. * 5.3 声明通知: 即额外加入功能对应的方法.
  29. * 5.3.1 前置通知: @Before("execution(public int com.spring.aop.ArithmeticCalculator.*(int, int))")
  30. * @Before 表示在目标方法执行之前执行 @Before 标记的方法的方法体.
  31. * @Before 里面的是切入点表达式:
  32. *
  33. * 6. 在通知中访问连接细节: 可以在通知方法中添加 JoinPoint 类型的参数, 从中可以访问到方法的签名和方法的参数.
  34. *
  35. * 7. @After 表示后置通知: 在方法执行之后执行的代码.
  36. */
  37. //通过添加 @Aspect 注解声明一个 bean 是一个切面!
  38. //需要把该类放入到IOC容器中,再声明为一个切面
  39. @Aspect
  40. @Component
  41. public class LoggingAspect {
  42. @Before("execution(public int com.spring.aop.ArithmeticCalculator.*(int, int))")
  43. public void beforeMethod(JoinPoint joinPoint){
  44. String methodName = joinPoint.getSignature().getName();
  45. Object [] args = joinPoint.getArgs();
  46. System.out.println("The method " + methodName + " begins with " + Arrays.asList(args));
  47. }
  48. //后置通知:在目标方法执行后(无论是否发生异常),执行的通知
  49. //在后置通知中还不能访问目标方法执行的结果,需要在返回通知里面去访问目标方法的返回通知
  50. @After("execution(* com.spring.aop.*.*(..))")
  51. public void afterMethod(JoinPoint joinPoint){
  52. String methodName = joinPoint.getSignature().getName();
  53. System.out.println("The method " + methodName + " ends");
  54. }
  55. /**
  56. * 定义一个方法, 用于声明切入点表达式. 一般地, 该方法中再不需要添入其他的代码.
  57. * 使用 @Pointcut 来声明切入点表达式.
  58. * 后面的其他通知直接使用方法名来引用当前的切入点表达式.
  59. */
  60. @Pointcut("execution(public int com.spring.aop.ArithmeticCalculator.*(..))")
  61. public void declareJointPointExpression(){}
  62. /**
  63. * 在方法法正常结束受执行的代码
  64. * 返回通知是可以访问到方法的返回值的!
  65. */
  66. @AfterReturning(value="declareJointPointExpression()",
  67. returning="result")
  68. public void afterReturning(JoinPoint joinPoint, Object result){
  69. String methodName = joinPoint.getSignature().getName();
  70. System.out.println("The method " + methodName + " ends with " + result);
  71. }
  72. /**
  73. * 在目标方法出现异常时会执行的代码.
  74. * 可以访问到异常对象; 且可以指定在出现特定异常时在执行通知代码
  75. */
  76. @AfterThrowing(value="declareJointPointExpression()",
  77. throwing="e")
  78. public void afterThrowing(JoinPoint joinPoint, Exception e){
  79. String methodName = joinPoint.getSignature().getName();
  80. System.out.println("The method " + methodName + " occurs excetion:" + e);
  81. }
  82. /**
  83. * 环绕通知需要携带 ProceedingJoinPoint 类型的参数.
  84. * 环绕通知类似于动态代理的全过程: ProceedingJoinPoint 类型的参数可以决定是否执行目标方法.
  85. * 且环绕通知必须有返回值, 返回值即为目标方法的返回值
  86. */
  87. /*
  88. @Around("execution(public int com.spring.aop.ArithmeticCalculator.*(..))")
  89. public Object aroundMethod(ProceedingJoinPoint pjd){
  90. Object result = null;
  91. String methodName = pjd.getSignature().getName();
  92. try {
  93. //前置通知
  94. System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));
  95. //执行目标方法
  96. result = pjd.proceed();
  97. //返回通知
  98. System.out.println("The method " + methodName + " ends with " + result);
  99. } catch (Throwable e) {
  100. //异常通知
  101. System.out.println("The method " + methodName + " occurs exception:" + e);
  102. throw new RuntimeException(e);
  103. }
  104. //后置通知
  105. System.out.println("The method " + methodName + " ends");
  106. return result;
  107. }
  108. */
  109. }

2.3(xml配置文件)

 

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  9. <!-- 自动扫描的包 -->
  10. <context:component-scan base-package="com.spring.aop"></context:component-scan>
  11. <!-- 使 AspectJ 的注解起作用 -->
  12. <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  13. </beans>

2.4(Main)

 

  1. package com.spring.aop;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. public class Main {
  5. public static void main(String[] args) {
  6. ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-aop.xml");
  7. ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
  8. System.out.println(arithmeticCalculator.getClass().getName());
  9. int result = arithmeticCalculator.add(11, 12);
  10. System.out.println("result:" + result);
  11. result = arithmeticCalculator.div(21, 3);
  12. System.out.println("result:" + result);
  13. }
  14. }

2.5(运行结果)

                     

2.6(总结)

通过上面的步骤以及运行结果我们可发现,运行的过程有点像动态代理,Spring的IOC在生成切面的时候会根据切点找到对应的bean,然后为其生成代理对象

3.(切面的优先级)

 

在同一个连接点上应用不止一个切面时, 除非明确指定, 否则它们的优先级是不确定的.

切面的优先级可以通过实现 Ordered 接口或利用 @Order 注解指定.

若使用 @Order 注解, 序号出现在注解中

                              

                               

4.(重用切入点定义)

 

在编写 AspectJ切面时, 可以直接在通知注解中书写切入点表达式. 但同一个切点表达式可能会在多个通知中重复出现.

AspectJ切面中, 可以通过 @Pointcut注解将一个切入点声明成简单的方法. 切入点的方法体通常是空的, 因为将切入点定义与应用程序逻辑混在一起是不合理的.

切入点方法的访问控制符同时也控制着这个切入点的可见性. 如果切入点要在多个切面中共用, 最好将它们集中在一个公共的类中. 在这种情况下, 它们必须被声明为 public. 在引入这个切入点时, 必须将类名也包括在内. 如果类没有与这个切面放在同一个包中, 还必须包含包名.

其他通知可以通过方法名称引入该切入点.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/674993
推荐阅读
相关标签
  

闽ICP备14008679号