0

Spring_AOP深度剖析

 8 months ago
source link: https://blog.51cto.com/u_13529088/8925772
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Spring_AOP深度剖析

精选 原创

清醒的人最荒唐 2023-12-21 17:30:56 ©著作权

文章标签 spring AOP 目标对象 文章分类 Java 后端开发 阅读数220

一 AOP 1.1 什么是AOP

AOP 面向切面编程。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

1.2 AOP底层实现

实际上,AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强。

Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。

在 Spring 中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。

当bean实现接口时,会用JDK代理模式 当bean没有实现接口,用cglib实现( 可以强制使用cglib(在spring配置中加入<aop:aspect jautoproxy proxyt-target-class=”true”/>)

1.3 AOP相关术语

Target(目标对象):代理的目标对象

Proxy (代理):一个类被 AOP 织入增强后,就产生一个结果代理类

Joinpoint(连接点):所谓连接点是指那些可以被拦截到的点。在spring中,这些点指的是方法,因为 spring只支持方法类型的连接点

Pointcut(切入点):所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义

1.3 基于(xml)AOP开发

  1. 创建java项目,导入AOP相关坐标

mysql mysql-connector-java 5.1.47 com.alibaba druid 1.1.15

org.springframework spring-context 5.1.5.RELEASE

org.aspectj aspectjweaver 1.8.13

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.1.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
<!--spring整合junit-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.1.5.RELEASE</version>
    </dependency>
</dependencies>
  1. 创建目标接口和目标实现类(定义切入点)(略)
  2. 创建通知类及方法(定义通知) (略)
  3. 将目标类和通知类对象创建权交给spring (略)
  4. 在核心配置文件中配置织入关系,及切面
  5. 编写测试代码(略)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK