0


Spring AOP -- 面相切面编程

AOP是Spring框架的核心之一,AOP是一种思想,它的实现方法有很多,有Spring AOP,也有AspectJ、CGLIB等。我们熟知的拦截器其实就是AOP思想的一种实现方式。

AOP是一种思想,是对某一类事情的集中处理。

Spring AOP的实现方式:

  1. 基于注解 @Aspect;
  2. 基于自定义注解;
  3. 基于Spring API(通过xml配置的方式);
  4. 基于代理来实现。

想要实现Spring Aop需要先引入以下依赖。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-aop</artifactId>
  4. </dependency>

例如:我们此时想要优化一个接口的执行效率

此时有一个接口如下:

  1. @RequestMapping("/aop")
  2. @RestController
  3. public class Main {
  4. @Autowired
  5. private ForService fs;
  6. @RequestMapping("/fun1")
  7. public void fun1() {
  8. fs.fun(3);
  9. for (int i = 0; i < 1000; i++) {};
  10. }
  11. }
  1. @Service
  2. public class ForService {
  3. public int fun(int i) {
  4. for (int j = 0; j < 3000; j++) {
  5. i++;
  6. }
  7. return i;
  8. }
  9. }

我们首先需要知道这个接口在执行过程中调用的各个方法的执行时间,然后再对每个方法进行针对性优化。用AOP思想来实现:

基于注解 @Aspect

  1. @Slf4j
  2. @Component
  3. @Aspect
  4. public class WritTime {
  5. @Around("execution(* com.example.Spring_demo.aop.*.*(..)))")
  6. public Object time(ProceedingJoinPoint pjp) throws Throwable {
  7. //记录开始时间
  8. long start = System.currentTimeMillis();
  9. //执行目标方法
  10. Object a = pjp.proceed();
  11. //打印方法执行时间。pjp.toShortString()方法会返回方法签名的简写
  12. log.info(pjp.toShortString()+":"+(System.currentTimeMillis()-start)+"ms");
  13. return a;
  14. }
  15. }

切点:也称之为"切入点",提供⼀组规则(切点表达式)告诉程序对哪些方法来进行功能增强;

连接点:满足切点表达式规则的方法,就是连接点。也就是可以被AOP控制的方法;

通知:就是具体要做的工作,指哪些重复的逻辑,也就是共性功能(最终体现为⼀个方法);

切面:切点+通知。

切面类:切面所在的类,一个切面类中可以包含多个切面。

切点表达式:

常见的切点表达式有两种表达方式:

  1. execution(……):根据方法的签名来匹配
  2. @annotation(……):根据注解匹配

访问修饰限定符和异常可以被省略。

*** :匹配任意字符,只匹配一个元素(返回类型,包,类名,方法或者方法参数)**

  • 包名使用 * 表示任意包(一层包使用一个*);
  • 类名使用 * 表示任意类;
  • 返回值使用 * 表示任意返回值类型;
  • 方法名使用 * 表示任意方法;
  • 参数使用 * 表示⼀个任意类型的参数。

.. :匹配多个连续的任意符号,可以通配任意层级的包,或任意类型,任意个数的参数

  • 使用 .. 配置包名,标识此包以及此包下的所有子包;
  • 可以使用 .. 配置参数,任意个任意类型的参数。

+:表示匹配当前类和其子类

通知类型:

  • @Around:环绕通知,此注解标注的通知方法在目标方法前后都被执行;
  • @Before:前置通知,此注解标注的通知方法在目标方法前被执行;
  • @After:后置通知,此注解标注的通知方法在目标方法后被执行;
  • @AfterReturning:返回后通知;
  • @AfterThrowing:异常后通知。

多种通知类型的执行顺序

现有如下接口:

  1. @Slf4j
  2. @RequestMapping("/aop")
  3. @RestController
  4. public class Main {
  5. @RequestMapping("/fun1")
  6. public void fun1() {
  7. log.info("执行fun1方法");
  8. }
  9. }

定义如下切面类,里面有多个切面。

  1. @Slf4j
  2. @Component
  3. @Aspect
  4. public class WritTime {
  5. @Around("execution(* com.example.Spring_demo.aop.*.*(..)))")
  6. public Object time(ProceedingJoinPoint pjp) throws Throwable {
  7. log.info("@Around 方法前");
  8. //执行目标方法
  9. Object a = pjp.proceed();
  10. log.info("@Around 方法后");
  11. return a;
  12. }
  13. @Before("execution(* com.example.Spring_demo.aop.*.*(..)))")
  14. public void before() {
  15. log.info("@Before 前置通知");
  16. }
  17. @After("execution(* com.example.Spring_demo.aop.*.*(..)))")
  18. public void After() {
  19. log.info("@After 后置通知");
  20. }
  21. @AfterReturning("execution(* com.example.Spring_demo.aop.*.*(..)))")
  22. public void AfterReturning() {
  23. log.info("@AfterReturning 返回后通知");
  24. }
  25. @AfterThrowing("execution(* com.example.Spring_demo.aop.*.*(..)))")
  26. public void AfterThrowing() {
  27. log.info("@AfterThrowing 异常后通知");
  28. }
  29. }

如果发生异常:

异常是可以再切面中被捕获的,但需要通知类型为@Around

@Pointcut

@Pointcut注解可以把公共的切点表达式提取出来,需要用到时引用该切入点表达式即可。

  1. @Slf4j
  2. @Component
  3. @Aspect
  4. public class WritTime {
  5. @Pointcut("execution(* com.example.Spring_demo.aop.*.*(..)))")
  6. public void pc(){}
  7. @Around("pc()")
  8. public Object time(ProceedingJoinPoint pjp) {
  9. log.info("@Around 方法前");
  10. //执行目标方法
  11. Object a = null;
  12. try {
  13. a = pjp.proceed();
  14. } catch (Throwable e) {
  15. }
  16. log.info("@Around 方法后");
  17. return a;
  18. }
  19. @Before("pc()")
  20. public void before() {
  21. log.info("@Before 前置通知");
  22. }
  23. @After("pc()")
  24. public void After() {
  25. log.info("@After 后置通知");
  26. }
  27. @AfterReturning("pc()")
  28. public void AfterReturning() {
  29. log.info("@AfterReturning 返回后通知");
  30. }
  31. @AfterThrowing("pc()")
  32. public void AfterThrowing() {
  33. log.info("@AfterThrowing 异常后通知");
  34. }
  35. }

声明的切面表达式也可以再其他切面类中使用但需要提前声明

  1. @Slf4j
  2. @Component
  3. @Aspect
  4. public class WritTime1 {
  5. //()里引用的切面表达式前必须加上全限定类名
  6. @Before("com.example.Spring_demo.aop.WritTime.pc()")
  7. public void before() {
  8. log.info("WritTime1通知");
  9. }
  10. }

多个切面类的执行顺序

  1. @Slf4j
  2. @RequestMapping("/aop")
  3. @RestController
  4. public class Main {
  5. @RequestMapping("/fun1")
  6. public void fun1() {
  7. log.info("执行fun1方法");
  8. }
  9. }

定义以下三个切面类,每个类里面只有一个切面:

  1. //第一个
  2. @Slf4j
  3. @Component
  4. @Aspect
  5. public class WritTime1 {
  6. @Before("execution(* com.example.Spring_demo.aop.*.*(..)))")
  7. public void before() {
  8. log.info("WritTime1通知");
  9. }
  10. }
  11. //第二个
  12. @Slf4j
  13. @Component
  14. @Aspect
  15. public class WritTime2 {
  16. @Before("execution(* com.example.Spring_demo.aop.*.*(..)))")
  17. public void before() {
  18. log.info("WritTime2通知");
  19. }
  20. }
  21. //第三个
  22. @Slf4j
  23. @Component
  24. @Aspect
  25. public class WritTime3 {
  26. @Before("execution(* com.example.Spring_demo.aop.*.*(..)))")
  27. public void before() {
  28. log.info("WritTime3通知");
  29. }
  30. }

如果存在多个切面类执行顺序默认是按照类名进行排序。

@Order

当存在多个切面类时可以通过@Order注解来定义各个切面类的优先级。

对上述切面类进行细微修改加上注解

  1. //第一个
  2. @Slf4j
  3. @Component
  4. @Aspect
  5. @Order(3)
  6. public class WritTime1 {
  7. ……
  8. }
  9. //第二个
  10. @Slf4j
  11. @Component
  12. @Aspect
  13. @Order(2)
  14. public class WritTime2 {
  15. ……
  16. }
  17. //第三个
  18. @Slf4j
  19. @Component
  20. @Aspect
  21. @Order(1)
  22. public class WritTime3 {
  23. ……
  24. }

基于自定义注解

使用自定义注解来计算方法的执行时间。

声明一个自定义注解:

  1. //表示该接口只能作用于方法
  2. @Target({ElementType.METHOD})
  3. //该接口的生命周期
  4. @Retention(RetentionPolicy.RUNTIME)
  5. public @interface Time {
  6. }

使用切面类实现该注解的功能:

  1. @Slf4j
  2. @Component
  3. @Aspect
  4. public class WritTime {
  5. //@annotation里面的值为要实现的目标注解的全限定类名
  6. @Around("@annotation(com.example.Spring_demo.aop.Time)")
  7. public Object time(ProceedingJoinPoint pjp) throws Throwable {
  8. //记录开始时间
  9. long start = System.currentTimeMillis();
  10. //执行目标方法
  11. Object a = pjp.proceed();
  12. //打印方法执行时间。pjp.toShortString()方法会返回方法签名的简写
  13. log.info(pjp.toShortString()+":"+(System.currentTimeMillis()-start)+"ms(注解实现)");
  14. return a;
  15. }
  16. }

给待测方法添加注解

  1. @Slf4j
  2. @RequestMapping("/aop")
  3. @RestController
  4. public class Main {
  5. @Autowired
  6. private ForService forService;
  7. @Time
  8. @RequestMapping("/fun1")
  9. public void fun1() {
  10. forService.fun(1);
  11. for (int i = 0; i < 10; i++) {}
  12. }
  13. }

给已有的注解进行功能的增强

还可以使用上面的方式给已有的注解进行功能的增强(给@RequestMapping注解添加可以打印接口执行时间的功能):

  1. @Slf4j
  2. @Component
  3. @Aspect
  4. public class WritTime {
  5. //@annotation里面的值为@RequestMapping注解的全限定类名
  6. @Around("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
  7. public Object time(ProceedingJoinPoint pjp) throws Throwable {
  8. //记录开始时间
  9. long start = System.currentTimeMillis();
  10. //执行目标方法
  11. Object a = pjp.proceed();
  12. //打印方法执行时间。pjp.toShortString()方法会返回方法签名的简写
  13. log.info(pjp.toShortString()+":"+(System.currentTimeMillis()-start)+"ms(注解实现)");
  14. return a;
  15. }
  16. }

AOP的优势:

  1. 代码无侵入:不修改原始的业务方法,就可以对原始的业务方法进行了功能的增强或者是功能的改变;
  2. 减少了重复代码;
  3. 提高开发效率;
  4. 维护方便。
标签: java spring aop

本文转载自: https://blog.csdn.net/2302_76339343/article/details/136184486
版权归原作者 晚餐是PM 所有, 如有侵权,请联系我们删除。

“Spring AOP -- 面相切面编程”的评论:

还没有评论