Spring(4、AOP)

不念不忘少年蓝@ 2022-06-14 05:19 343阅读 0赞

注:本文用到的jar请到Spring(1-1、基于xml装配Bean)中查找

AOP(Aspect-OrientedProgramming,面向切面编程): 是一种新的方法论, 是对传统 OOP(Object-Oriented Programming, 面向对象编程) 的补充.

AOP 的主要编程对象是切面(aspect), 而切面模块化横切关注点.

在应用 AOP 编程时, 仍然需要定义公共功能, 但可以明确的定义这个功能在哪里, 以什么方式应用, 并且不必修改受影响的类. 这样一来横切关注点就被模块化到特殊的对象(切面)里.

AOP的好处:

每个事物逻辑位于一个位置, 代码不分散, 便于维护和升级

业务模块更简洁, 只包含核心业务代码.

专业术语

切面(Aspect): 横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象

通知(Advice): 切面必须要完成的工作

目标(Target): 被通知的对象

代理(Proxy): 向目标对象应用通知之后创建的对象

连接点(Joinpoint):程序执行的某个特定位置:如类某个方法调用前、调用后、方法抛出异常后等。连接点由两个信息确定:方法表示的程序执行点;相对点表示的方位

切点( pointcut ): 每个类都拥有多个连接点:例如 ArithmethicCalculator 的所有方法实际上都是连接点,即 连接点是程序类中客观存在的事务AOP 通过切点定位到特定的连接点。类比:连接点相当于数据库中的记录,切点相当于查询条件。切点和连接点不是一对一的关系,一个切点匹配多个连接点,切点通过 org.springframework.aop.Pointcut 接口进行描述,它使用类和方法作为连接点的查询条件。

启用AspectJ注解(基于注解)

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

将 aop Schema 添加到 根元素中.

要在 Spring IOC 容器中启用 AspectJ 注解支持, 只要在 Bean 配置文件中定义一个空的 XML 元素

当 Spring IOC 容器侦测到 Bean 配置文件中的 元素时, 会自动为与 AspectJ 切面匹配的 Bean 创建代理.

1、导入的jar包(见同类文章第一篇)

2、在配置文件中加入如下配置

  1. <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

把横切关注点的代码抽象到切面类中。

切面首先是一个IOC中的bean,及假日@Component注解

切面还需要加入@Aspect注解

3、在类中申明各种通知

申明一个方法

在方法前面加入@Before注解

4、可以在通知方法中声明一个类型为JoinPoint的参数,然后就能访问链接细节,入方法名称和参数值

  1. // 通过添加 @Aspect 注解声明一个 bean 是一个切面!
  2. @Aspect
  3. @Component
  4. public class LoggingAspect {
  5. @Before("execution(* com.spring.aop.helloworld.*.*(int,int))")
  6. public void beforeMethod(JoinPoint joinPoint) {
  7. String methodName = joinPoint.getSignature().getName();
  8. Object[] args = joinPoint.getArgs();
  9. System.out.println("The method " + methodName + " begins with "
  10. + Arrays.asList(args));
  11. }
  12. }

利用方法签名编写 AspectJ 切入点表达式

最典型的切入点表达式时根据方法的签名来匹配各种方法:

execution *com.atguigu.spring.ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 中声明的所有方法,第一个 *代表任意修饰符及任意返回值.第二个 * 代表任意方法. ..匹配任意数量的参数. 若目标类与接口与该切面在同一个包中, 可以省略包名.

execution public *ArithmeticCalculator.*(..): 匹配ArithmeticCalculator 接口的所有公有方法.

execution publicdouble ArithmeticCalculator.*(..): 匹配 ArithmeticCalculator 中返回 double类型数值的方法

execution publicdouble ArithmeticCalculator.*(double, ..): 匹配第一个参数为 double 类型的方法, .. 匹配任意数量任意类型的参数

execution public double ArithmeticCalculator.*( double,double): 匹配参数类型为 double, double 类型的方法

示例

在 AspectJ 中, 切入点表达式可以通过操作符 &&, ||, ! 结合起来.

20170611112016001

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

20170611112138252

JoinPoint:标识这个方法是个前置通知, 切点表达式表示执行任意类的任意方法.

第一个 *代表匹配任意修饰符及任意返回值,

第二个*代表任意类的对象,

第三个*代表任意方法,参数列表中的

.. 匹配任意数量的参数

前置通知

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

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

20170611112404862

标识这个方法是个前置通知, 切点表达式表示执行 ArithmeticCalculator

接口的 add() 方法. * 代表匹配任意修饰符及任意返回值, 参数列表中的 ..

匹配任意数量的参数

后置通知

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

一个切面可以包括一个或者多个通知.

20170611112505613

返回通知

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

20170611112603207

异常通知

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

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

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

20170611112737021

环绕通知

20170611112839607

xml配置

  1. <context:component-scan base-package="com.spring.beans.aop.annotation"></context:component-scan>
  2. <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

测试类

  1. ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
  2. ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx.getBean("arithmeticCalculator");
  3. System.out.println(arithmeticCalculator.getClass().getName());
  4. int result = arithmeticCalculator.add(11, 12);
  5. System.out.println("result:" + result);

基于xml配置aop

定义接口

  1. public interface ArithmeticCalculator {
  2. int add(int i, int j);
  3. int sub(int i, int j);
  4. int mul(int i, int j);
  5. int div(int i, int j);
  6. }

实现类

  1. public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
  2. public int add(int i, int j) {
  3. int result = i + j;
  4. return result;
  5. }
  6. public int sub(int i, int j) {
  7. int result = i - j;
  8. return result;
  9. }
  10. public int mul(int i, int j) {
  11. int result = i * j;
  12. return result;
  13. }
  14. public int div(int i, int j) {
  15. int result = i / j;
  16. return result;
  17. }
  18. }

定义切面

  1. package com.spring.beans.aop.xml;
  2. import java.util.Arrays;
  3. import org.aspectj.lang.JoinPoint;
  4. import org.aspectj.lang.ProceedingJoinPoint;
  5. public class LoggerAspect {
  6. public void beforeMethod(JoinPoint joinPoint) {
  7. String name = joinPoint.getSignature().getName();
  8. Object[] args = joinPoint.getArgs();
  9. System.out.println("The method after" + name + " begins with"
  10. + Arrays.asList(args));
  11. }
  12. public void afterMethod(JoinPoint joinPoint) {
  13. String name = joinPoint.getSignature().getName();
  14. Object[] args = joinPoint.getArgs();
  15. System.out.println("The method div" + name + " begins with"
  16. + Arrays.asList(args));
  17. }
  18. public void afterReturning(JoinPoint joinPoint) {
  19. String name = joinPoint.getSignature().getName();
  20. Object[] args = joinPoint.getArgs();
  21. System.out.println("The method div" + name + " begins with"
  22. + Arrays.asList(args));
  23. }
  24. public void afterThrowing(JoinPoint joinPoint, Exception e) {
  25. String name = joinPoint.getSignature().getName();
  26. // Object[] args = joinPoint.getArgs();
  27. System.out.println("The method div" + name + " begins with" + e);
  28. }
  29. public Object aroundMethod(ProceedingJoinPoint pjd) {
  30. Object r = null;
  31. String name = pjd.getSignature().getName();
  32. try {
  33. // 前置通知
  34. System.out.println("The method " + name + " begins with"
  35. + Arrays.asList(pjd.getArgs()));
  36. r = pjd.proceed();
  37. // 后置通知
  38. System.out.println("The method " + name + " ends with"
  39. + Arrays.asList(pjd.getArgs()));
  40. } catch (Throwable e) {
  41. e.printStackTrace();
  42. System.out.println("The method " + name + " occurs with"
  43. + Arrays.asList(pjd.getArgs()));
  44. }
  45. return r;
  46. }
  47. }

xml配置

  1. <bean id="arithmeticCalculator" class="com.spring.beans.aop.xml.ArithmeticCalculatorImpl">
  2. </bean>
  3. <bean id="loggerAspect" class="com.spring.beans.aop.xml.LoggerAspect"></bean>
  4. <bean id="validationAspect" class="com.spring.beans.aop.xml.ValidationAspect"> </bean>
  5. <!-- 配置aop -->
  6. <aop:config>
  7. <!-- 配置切点表达式 -->
  8. <aop:pointcut id="pointCut"
  9. expression="execution(* com.spring.beans.aop.xml.ArithmeticCalculator.*(*,*))" />
  10. <!-- 配置切面及通知 -->
  11. <aop:aspect ref="loggerAspect" order="2">
  12. <aop:before method="beforeMethod" pointcut-ref="pointCut" />
  13. <aop:after method="afterMethod" pointcut-ref="pointCut" />
  14. <aop:after-throwing method="afterThrowing" pointcut-ref="pointCut" throwing="e" />
  15. <aop:after-returning method="afterReturning" pointcut-ref="pointCut"
  16. returning="result" />
  17. <!-- 环绕通知 -->
  18. <!-- <aop:around method="aroundMethod" pointcut-ref="pointCut" /> -->
  19. </aop:aspect>
  20. <aop:aspect ref="validationAspect" order="1">
  21. <aop:before method="validationAspect" pointcut-ref="pointCut" />
  22. </aop:aspect>
  23. </aop:config>

测试类

  1. ApplicationContext ctx = new ClassPathXmlApplicationContext(
  2. "applicationContext-xml.xml");
  3. ArithmeticCalculator arithmeticCalculator = (ArithmeticCalculator) ctx
  4. .getBean("arithmeticCalculator");
  5. System.out.println(arithmeticCalculator.getClass().getName());
  6. int div = arithmeticCalculator.div(12, 0);
  7. System.out.println(div);
  8. }

发表评论

表情:
评论列表 (有 0 条评论,343人围观)

还没有评论,来说两句吧...

相关阅读

    相关 4.Spring AOP理解

    1. AOP原理 AOP将应用系统分为两部分,核心业务逻辑(Core business concerns)及横向的通用逻辑,也就是所谓的方面Crosscuttin