SpringMVC 第十六章 Spring 的 AOP 简介


SpringMVC —— 第十六章 Spring 的 AOP 简介


1. 什么是 AOP

AOPA spect O riented P rogramming 的编写,意为 面向切面编程 ,是通过预编译方式和运行期动态代理实现程序功能的统一维护的技术。

AOP 是 OOP 的延续,是软件开发中的一个热点,也是 Spring 框架中的一个重要内容,是函数式编程的一种衍生泛型。利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可用性,同时提高了开发的效率。

2. AOP 的作用和优势

  • 作用:在程序运行期间,在不修改源代码的情况下对方法进行功能增强
  • 优势:减少重复代码,提高开发效率,并且便于维护

3. AOP 的底层实现

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

4. AOP 的动态代理技术

常用的动态代理技术

  • JDK代理:基于接口的动态代理技术
  • CGLIB代理:基于父类的动态代理技术

AOPDynamciProxy

5. JDK 的动态代理

示例代码:

com.yourname.proxy.jdk.TargetInterface

/**
 * @author gregPerlinLi
 * @since 2021-09-15
 */
public interface TargetInterface {
     void save();
}

com.yourname.jdk.impl.Target

/**
 * @author gregPerlinLi
 * @since 2021-09-15
 */
public class Target implements TargetInterface {
    @Override
    public void save() {
        System.out.println("Save running...");
    }
}

com.yourname.jdk.Enhance

/**
 * @author gregPerlinLi
 * @since 2021-09-15
 */
public class Enhance {
    public void front() {
        System.out.println("Front enhance...");
    }
    public void post() {
        System.out.println("Post enhance...");
    }
}

com.yourname.jdk.ProxyTest

/**
 * @author gregPerlinLi
 * @since 2021-09-15
 */
public class ProxyTest {
    public static void main(String[] args) {
        // Create target object
        final Target target = new Target();
        // Get enhance object
        Enhance enhance = new Enhance();
        // The return value is the dynamically generated proxy object
        TargetInterface proxyInstance = (TargetInterface) Proxy.newProxyInstance(
                // Classloader for target object
                target.getClass().getClassLoader(),
                // An array of bytecode objects that are the same as the target object
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    // Any method that calls a proxy object actually executes the invoke method
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        // Pre enhancement
                        enhance.front();
                        // Execution target method
                        Object invoke = method.invoke(target, args);
                        // Post enhancement
                        enhance.post();
                        return invoke;
                    }
                }
        );
        // Call the method of the proxy object
        proxyInstance.save();
    }
}

6. CGLIB 的动态代理

示例代码:

pom.xml

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.9</version>
</dependency>

com.yourname.proxy.cglib.Target

/**
 * @author gregPerlinLi
 * @since 2021-09-15
 */
public class Target &#123;
    public void save() &#123;
        System.out.println("Save running...");
    &#125;
&#125;

com.yourname.proxy.cglib.Enhance

/**
 * @author gregPerlinLi
 * @since 2021-09-15
 */
public class Enhance &#123;
    public void front() &#123;
        System.out.println("Front enhance...");
    &#125;
    public void post() &#123;
        System.out.println("Post enhance...");
    &#125;
&#125;

com.yourname.proxy.cglib.ProxyTest

/**
 * @author gregPerlinLi
 * @since 2021-09-15
 */
public class ProxyTest &#123;
    public static void main(String[] args) &#123;
        // Create target object
        final Target target = new Target();
        // Get enhance object
        Enhance enhance = new Enhance();
        // Call the method of the proxy object based on CGLIB
        // 1. Create intensifier
        Enhancer enhancer = new Enhancer();
        // 2. Set parent (target)
        enhancer.setSuperclass(com.gregperlinli.proxy.cglib.Target.class);
        // 3. Set callback function
        enhancer.setCallback(new MethodInterceptor() &#123;
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable &#123;
                // Pre enhancement
                enhance.front();
                // Execution target method
                Object invoke = method.invoke(target, args);
                // Post enhancement
                enhance.post();
                return invoke;
            &#125;
        &#125;);
        // 4. Generate a proxy object
        Target proxyInstance = (Target) enhancer.create();
        // Call the method of the proxy object
        proxyInstance.save();
    &#125;
&#125;

7. AOP 相关概念

Spring 的 AOP 实现底层就是对上面的动态代理进行了封装,封装后我们只需要对需要关注的部分进行代码编写。并通过配置的方式完成指定目标的方法增强

在正式开始 AOP 操作之前,需要先了解 AOP 的相关术语,常用的术语如下:

  • Target(目标对象):代理的目标对象
  • Proxy(代理):一个类被 AOP 织入增强后,就产生一个结果代理类
  • Joinpoint(连接点):所谓的连接点就是指那些被拦截到的点。在 Spring 中,这些点指的是方法,因为 Spring 只支持方法类型的连接点
  • Pointcut(切入点): 所谓的切入点就是指我们要对哪些 Joinpoint 进行拦截定义
  • Advice/Enhance(通知/增强): 所谓的通知是指拦截到 Joinpoint 之后所要做的事情
  • Aspect(切面): 是切入点和通知(引介)的结合
  • Weaving(织入): 是指把增强应用到目标对象来创建新的代理对象的过程。Spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载织入

8. AOP 开发明确的事项

8.1. 需要编写的内容

  • 编写核心业务代码(目标类的目标方法)
  • 编写切面类,切面类中有通知(增强方法)
  • 在配置文件中,配置织入关系,即将哪些通知与哪些连接点进行结合

8.2. AOP 技术实现的内容

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

8.3. AOP 底层使用哪种代理方式

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

9. 知识要点

  • AOP:面向切面编程
  • AOP 底层实现:基于 JDK 的动态代理和基于 CGLIB 的动态代理
  • AOP 的重点概念:
    • Pointcut(切入点): 所谓的切入点就是指我们要对哪些 Joinpoint 进行拦截定义
    • Advice/Enhance(通知/增强): 所谓的通知是指拦截到 Joinpoint 之后所要做的事情
    • Aspect(切面): 是切入点和通知(引介)的结合
    • Weaving(织入): 是指把增强应用到目标对象来创建新的代理对象的过程。Spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载织入
  • 开发明确事项:
    • 谁是切点(切点表达式配置)
    • 谁是通知(切面中的增强方法)
    • 将切点和通知进行织入配置


文章作者: gregPerlinLi
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 gregPerlinLi !
  目录