前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring 复盘 | AOP

Spring 复盘 | AOP

作者头像
JavaFish
发布2019-10-17 13:13:57
3080
发布2019-10-17 13:13:57
举报

Spring AOP 基础 Java 动态代理实现,阅读文章之前,你最好有以下基础:

java动态代理

1、什么是 AOP ?

AOP(Aspect Oriented Programming),即面向切面编程,它是 OOP(Object Oriented Programming,面向对象编程)的补充和完善。

在开发中,功能点通常分为横向关注点和核心关注点,核心关注点就是业务关注的点,大部分是要给用户看的。而横向关注点是用户不关心,而我们程序又必须实现的,它的特点是横向分布于核心关注点各处,比如日志功能,核心关注点:增删改查都需要实现日志功能。如果用 面向对象编程来实现的话,那增删改查都需要写一遍日志代码,这会造成非常多冗余代码,显然是不合理的。而此时,AOP 应运而生。它统一定义了,何时、何处执行这些横向功能点

2、AOP 相关术语 要理解 AOP 首先要认识以下相关术语,有这么个场景,我需要给用户模块的增删改查,实现日志功能,我现在通过这个场景来解释以上术语。

  • 连接点(joinpoint)

被拦截到的点,因为 Spring 只支持方法类型的连接点,所以在 Spring 中连接点指的就是被拦截到的方法。场景中,连接点就是增删改查方法本身。

  • 通知(advice)

所谓通知指的就是指拦截到连接点之后要执行的代码,通知分为前置、后置、异常、最终、环绕通知五类。 1、前置通知(Before):在目标方法被调用之前调用通知功能; 2、后置通知(After):在目标方法完成之后调用通知,此时不会关 心方法的输出是什么; 3、返回通知(After-returning):在目标方法成功执行之后调用通 知; 4、异常通知(After-throwing):在目标方法抛出异常后调用通知; 5、环绕通知(Around):通知包裹了被通知的方法,在被通知的方 法调用之前和调用之后执行自定义的行为。

  • 切点(pointcut)

对连接点进行拦截的定义,它会匹配通知所要织入的一个或多个连接点。它的格式是这样的:

来自 Spring4 实战

  • 切面(aspect)

类是对物体特征的抽象,切面就是对横切关注点的抽象,它定义了切点和通知。场景中,日志功能就是这个抽象,它定义了你要对拦截方法做什么?切面是通知和切点的结合。通知和切点共同定义了切面的全部内容——它是什么,在何时和何处完成其功能。

  • 织入(weave)

将切面应用到目标对象并导致代理对象创建的过程

  • 引入(introduction)

在不修改代码的前提下,引入可以在运行期为类动态地添加一些方法或字段

3、注解实现 AOP

首先,定义一个加减乘除的接口,代码如下:

代码语言:javascript
复制
 1 public interface ArithmeticCalculator {
 2
 3     int add(int i, int j);
 4
 5     int sub(int i, int j);
 6
 7     int mul(int i, int j);
 8
 9     int div(int i, int j);
10
11 }

定义一个实现类,代码如下:

代码语言:javascript
复制
 1 @Component("arithmeticCalculator")
 2 public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
 3
 4     public int add(int i, int j) {
 5         int result = i + j;
 6         return result;
 7     }
 8
 9     public int sub(int i, int j) {
10         int result = i - j;
11         return result;
12     }
13
14     public int mul(int i, int j) {
15         int result = i * j;
16         return result;
17     }
18
19     public int div(int i, int j) {
20         int result = i / j;
21         return result;
22     }
23
24 }

定义切面,代码如下:

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

xml 配置,代码如下:

代码语言:javascript
复制
 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     <!-- 自动扫描的包 -->
11     <context:component-scan base-package="com.nasus.spring.aop.impl"></context:component-scan>
12
13     <!-- 使 AspectJ 的注解起作用 -->
14     <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
15 <
16

测试方法:

代码语言:javascript
复制
 1 public class Main {
 2
 3     public static void main(String args[]){
 4
 5         // 1、创建 Spring 的 IOC 容器
 6         ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext_aop.xml");
 7
 8         // 2、从 IOC 容器中获取 bean 实例
 9         ArithmeticCalculator arithmeticCalculator = ctx.getBean(ArithmeticCalculator.class);
10
11         // 3、使用 bean
12         arithmeticCalculator.add(3,6);
13     }
14
15 }

测试结果:

代码语言:javascript
复制
1 The method add begins with [3, 6]
2 The method add begins with [3, 6]
3 The method add ends with 9
4 The method add ends
5 The method add ends
6 The method add ends with 9

4、xml 实现 AOP

关于 xml 的实现方式,网上发现一篇文章写的不错,此处,不再赘述,有兴趣的参考以下链接:

https://www.cnblogs.com/hongwz/p/5764917.html

5、源码地址

https://github.com/turoDog/review_spring

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-08-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 一个优秀的废人 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档