跳至主要內容

Spring AOP

晨光-向大约 10 分钟JavaSpringJavaSpring

Spring AOP

1. 概述

1. 什么是AOP

AOP:全称是 Aspect Oriented Programming 即:面向切面编程

简单的说它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强。

2. AOP优势

作用:
	在程序运行期间,不修改源码对已有方法进行增强。
优势:
    减少重复代码
    提高开发效率
    维护方便

3. AOP 的实现方式

使用动态代理技术

2. AOP术语

1. Joinpoint(连接点): 所谓连接点是指那些被拦截到的点。在 spring 中,这些点指的是方法,因为 spring 只支持方法类型的连接点。 [业务层的方法]
2. Pointcut(切入点): 所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义。[切入点: 被增强的方法, 并不是所有的连接点都是,只有被增强的方法才称为"切入点" ]
3. Advice(通知/增强): 所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。
4. Introduction(引介): 引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方法或 Field。
5. Target(目标对象): 代理的目标对象。
6. Weaving(织入): 是指把增强应用到目标对象来创建新的代理对象的过程。spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。
7. Proxy(代理): 一个类被 AOP 织入增强后,就产生一个结果代理类。
8. Aspect(切面): 是切入点和通知(引介)的结合。

3. AOP使用

<!--AspectJ: 解析切入点表达式-->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.5</version>
</dependency>

1. 切入点表达式

1). 关键字: execution(表达式)
2). 表达式:
        访问修饰符 返回值 包名.包名.包名...类名.方法名.(参数列表)
3). 标准写法:
        public void com.chggx.service.impl.AccountServiceImpl.saveAccount()
        PS: 1. 访问修饰符省略:  void com.chggx.service.impl.AccountServiceImpl.saveAccount()
            2. 返回值可以使用任意通配符,表示任意返回值:  * com.chggx.service.impl.AccountServiceImpl.saveAccount()
            3. 包名可以使用统配符,表示任意包(注意: 有几级包,就写几个"*"):  * *.*.*.AccountServiceImpl.saveAccount()
            4. 可以使用 "..": 表示当前包及其子包:  * *..AccountServiceImpl.saveAccount()
            5. 类名和方法名都可以使用 "*" 来实现通配 * *..*.*()
            6. 参数列表:
                    1. 可以直接写数据类型
                        1. 基本类型: 直接写名称  [int]: * *..*.*(int)
                        2. 引用类型: "包名.类名" 方式  [java.lang.String]
                    2. 可以直接使用统配符 "*" 表示任意类型,但必须有参数:  * *..*.*(*)
                    3. 可以使用 "..": 表示有无参数均可,有参数可以是任意类型: * *..*(..)
4). 全通配符写法
        * *..*(..)
5). 实际开发过程中切入点表达式的通常写法:
        切到业务层实现类下的所有方法:  * com.chggx.service.impl.*.*(..)

2. spring基于XML的AOP配置

1. 把通知Bean也交给spring来管理
2. 使用 aop:config 标签表名开始AOP的配置
3. 使用 aop:aspect 标签表名配置切面
        id属性: 给切面提供一个唯一ID
        ref属性: 是指定通知类bean的id
4. 在 aop:aspect 标签的内部使用对应标签来配置通知类型
1. 入门
springAOP01
springAOP01
  • 配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置spring ioc: 把service对象配置进来 连接点: 业务层的方法-->
    <bean id="accountService" class="com.chggx.service.impl.AccountServiceImpl"/>

    <!--配置Logger类: 用于增强业务层的方法(记录日志)-->
    <bean id="logger" class="com.chggx.utils.Logger"/>

    <!--配置AOP-->
    <aop:config>
        <!--配置切面-->
        <aop:aspect id="logAdvice" ref="logger">
            <!--
                1. 配置通知类型: 前置通知
                2. 通知方法: printLog() Logger类中的方法
                3. 切入点表达式: execution(public void com.chggx.service.impl.AccountServiceImpl.saveAccount()): 用于增强的方法
            -->
            <aop:before method="printLog"
                        pointcut="execution(public void com.chggx.service.impl.AccountServiceImpl.saveAccount())"/>
        </aop:aspect>
    </aop:config>

</beans>
2. 通知类型
通知类型作用
前置通知在切入点方法执行之前执行before
后置通知在切入点方法正常执行之后执行. (它和异常通知永远只会执行一个)after-returning
异常通知在切入点方法执行产生异常之后执行. (它和后置通知永远只会执行一个)after-throwing
最终通知无论切入点方法是否正常执行,它都会在其后面执行after
环绕通知一种可以在代码中手动控制增强方法何时执行的方式。[推荐}around
1. xml写法
<!--配置AOP-->
<aop:config>
    <!--配置切面-->
    <aop:aspect id="logAdvice" ref="logger">
        <!--前置通知: 在切入点方法执行之前执行-->
        <aop:before method="beforePrintLog" pointcut="execution(public void com.chggx.service.impl.AccountServiceImpl.saveAccount())"/>
        <!--后置通知: 在切入点方法正常执行之后执行. (它和异常通知永远只会执行一个)-->
        <aop:after-returning method="afterReturningPrintLog" pointcut="execution(public void com.chggx.service.impl.AccountServiceImpl.saveAccount())"/>
        <!--异常通知: 在切入点方法执行产生异常之后执行. (它和后置通知永远只会执行一个)-->
        <aop:after-throwing method="afterThrowPrintLog" pointcut="execution(public void com.chggx.service.impl.AccountServiceImpl.saveAccount())"/>
        <!--最终通知: 无论切入点方法是否正常执行,它都会在其后面执行-->
        <aop:after method="afterPrintLog" pointcut="execution(public void com.chggx.service.impl.AccountServiceImpl.saveAccount())"/>
    </aop:aspect>
</aop:config>
2. 优化代码
  • 在标签</aop:aspect>内
  • 在标签 </aop:aspect>外
3. 环绕通知 😄
1. 环绕通知问题
  • 配置文件
<!--配置AOP-->
<aop:config>
    <!--
         配置切入点表达式:
      -->
    <aop:pointcut id="ptl" expression="execution(* com.chggx.service.impl.*.*(..))"/>
    <!--配置切面-->
    <!-- pointcut-ref属性: 用于配置切入点表达式-->
    <aop:aspect id="logAdvice" ref="logger">
        <!--配置环绕通知: 详细注释(Logger类)-->
        <aop:around method="aroundPrintLog" pointcut-ref="ptl"/>
    </aop:aspect>
</aop:config>
  • 方法
/**
 * 环绕通知方法
 */
public void aroundPrintLog(){
    System.out.println("环绕通知log中的before...");
}


// 被增强的方法
    @Override
    public void saveAccount() {
        System.out.println("save...");
    }
  • 结果
E:\develop\Java\jdk1.8.0_91\bin\java.exe -
环绕通知log中的before...
  • 问题:
    当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了?
2. 解决

通过代理的方式实现事务控制分析

1. 分析:
       通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有。
2. 解决:
       Spring框架为我们提供了一个接口:"ProceedingJoinPoint"。"该接口有一个方法proceed()",此方法就相当于明确调用"切入点方法"。
       该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。
3. spring中的环绕通知:
       它是spring框架为我们提供的"一种可以在代码中手动控制增强方法何时执行的方式。"
       可以使用代码的方式实现其余4中通知
public Object aroundPrintLog(ProceedingJoinPoint point) {
    Object reValue = null;
    try {
        // 得到方法执行所需要的参数
        Object[] args = point.getArgs();
        System.out.println("环绕通知log中的...前置通知");
        // 明确调用业务层方法(切入点方法)
        reValue = point.proceed(args);
        System.out.println("环绕通知log中的...后置通知");

        return reValue;
    } catch (Throwable throwable) {
        System.out.println("环绕通知log中的...异常通知");
        throw new RuntimeException(throwable);
    } finally {
        System.out.println("环绕通知log中的...最终通知");
    }
}

3. 基于注解AOP配置 推荐环绕通知

通知类型作用
前置通知在切入点方法执行之前执行@Before
后置通知在切入点方法正常执行之后执行. (它和异常通知永远只会执行一个)@AfterReturning
异常通知在切入点方法执行产生异常之后执行. (它和后置通知永远只会执行一个)@AfterThrowing
最终通知无论切入点方法是否正常执行,它都会在其后面执行@Ater
环绕通知一种可以在代码中手动控制增强方法何时执行的方式。[推荐]@Around
1. 配置
  • XML配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.chggx"/>

    <!--配置spring开启注解AOP的支持-->
    <aop:aspectj-autoproxy/>

</beans>
  • 注解配置
@Configuration
@ComponentScan(basePackages="com.itheima")
@EnableAspectJAutoProxy
public class SpringConfiguration {
}
2. 通知类
@Component("logger")
@Aspect // 当前类是一个切面类
public class Logger {

    @Pointcut("execution(* com.chggx.service.impl.*.*(..))")
    private void ptl(){

    }

    /**
     * 前置通知
     */
    @Before("ptl()")
    public void beforePrintLog() {
        System.out.println("前置通知log中的before...");
    }

    /**
     * 后置通知
     */
    @AfterReturning("ptl()")
    public void afterReturningPrintLog() {
        System.out.println("后置通知log中的afterReturning...");
    }

    /**
     * 异常通知
     */
    @AfterThrowing("ptl()")
    public void afterThrowPrintLog() {
        System.out.println("异常通知log中的afterThrow...");
    }

    /**
     * 最终通知
     */
    @After("ptl()")
    public void afterPrintLog() {
        System.out.println("最终通知log中的after...");
    }

    /**
     * 环绕通知
     * 1. 问题:
     * 当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了
     * 2. 分析:
     * 通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有。
     * 3. 解决:
     * Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。
     * 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。
     * <p>
     * 4. spring中的环绕通知:
     * 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。
     */
    @Around("ptl()")
    public Object aroundPrintLog(ProceedingJoinPoint point) {
        Object reValue = null;
        try {
            // 得到方法执行所需要的参数
            Object[] args = point.getArgs();
            System.out.println("环绕通知log中的...前置通知");
            // 明确调用业务层方法(切入点方法)
            reValue = point.proceed(args);
            System.out.println("环绕通知log中的...后置通知");

            return reValue;
        } catch (Throwable throwable) {
            System.out.println("环绕通知log中的...异常通知");
            throw new RuntimeException(throwable);
        } finally {
            System.out.println("环绕通知log中的...最终通知");
        }
    }

}

当我们使用.我们推荐使用环绕通知,因为其余4个通知在使用时,最终通知在后置通知之前执行

前置通知log中的before...
save...
最终通知log中的after...
后置通知log中的afterReturning...

参考文档:

https://www.zhihu.com/question/377582556open in new window

Spring 一开始最强大的就是 IOC / AOP 两大核心功能,我们今天一起来学习一下 Spring AOP 常见注解和执行顺序。Spring Aop 的常用注解首先我们一起来回顾一下 Spring Aop 中常用的几个注解:
@Before 前置通知:目标方法之前执行
@After 后置通知:目标方法之后执行(始终执行)
@AfterReturning 返回之后通知:执行方法结束之前执行(异常不执行)@AfterThrowing 异常通知:出香异常后执行 
@Around 环绕通知:环绕目标方法执行

SpringBoot AOP获取@RequestBody参数open in new window

SpringBoot使用AOP获取请求参数open in new window