Spring框架6:面向切面编程(AOP)

本系列笔记均是对b站教程https://www.bilibili.com/video/av47952931 的学习笔记,非本人原创

AOP(面向切面编程)

在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
来源:https://baike.baidu.com/item/AOP/1332219
AOP的作用:在程序运行期间,不修改源码已有方法进行增强。减少重复代码、提供开发效率、维护方便
AOP的实现需要使用动态代理

AOP相关术语

enter description here
被代理对象的所有方法都被称为连接点,而只有被代理的方法才被称为是切入点。所以切入点是连接点的一个子集
enter description here

  • 前置通知:在执行业务之前执行的操作被称为是前置通知;相应地,之后执行的被称为是后置通知
  • catch中的操作被称为是异常通知,finally中的是最终通知
  • 整个invoke方法被执行就是环绕通知:在环绕通知中,有明确的切入点方法调用
    enter description here

学习spring的AOP要明确的事情

enter description here

spring基于XML的AOP

先介绍一下项目结构:
enter description here
业务层我们只做很简单的模拟实现:

package com.jiading.service;
/*
账户的业务层接口
 */
public interface IAccountService {
    /*
    这里的方法是为了表现返回值和参数的情况,不纠结于具体的功能
     */
    /*
    模拟保存账户
    无返回值无参
     */
    void saveAccount();
    /*
    模拟更新账户
    无返回值有参数
     */
    void updateAccount(int i);
    /*
    模拟删除账户
    有返回值无参
     */
    int deleteAccount();
}
package com.jiading.service.impl;

import com.jiading.service.IAccountService;

/*
账户业务层实现类
 */
public class AccountServiceImpl implements IAccountService {

    public void saveAccount() {
        System.out.println("执行了保存");
    }

    public void updateAccount(int i) {
        System.out.println("执行了更新"+i);
    }

    public int deleteAccount() {
        System.out.println("执行了删除");
        return 0;
    }
}

Logger是我们切入进去用来增强其他方法的方法:

package com.jiading.utils;
/*
用于记录日志的工具类,提供了公共代码
 */
public class Logger {
    /*
    用于向控制台打印日志,计划让其在切入点方法执行之前执行(切入点方法就是业务层方法)
     */
    public void printLog(){
        System.out.println("Logger类中的printLoh方法开始记录日志");

    }
}

最重要的是这个配置文件:
bean.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"
       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">

    <!-- 配置spring的ioc,把service对象配置进来-->
    <bean id="accountService" class="com.jiading.service.impl.AccountServiceImpl"></bean>
    <!-- spring中基于xml的aop配置步骤
    1. 把通知的bean也交给spring管理
    2. 使用aop:config标签表明开始aop的配置
    3. 使用aop:aspect标签表明开始配置切面
        id属性是给切面提供一个唯一标志
        ref属性是指定通知类bean的id
    4. 在aop:aspect标签内部使用对应标签来配置通知类型
        我们现在的示例是让printLog方法在切入点方法执行之前执行,所以是前置通知,所以使用aop:before表示配置前置通知
            method用于指定logger类中哪个方法是前置通知
            pointcut属性用于指定切入点表达式,指的是对业务层哪些方法进行增强
        切入点表达式的写法:
            关键字:execution(表达式)
            表达式:
                访问修饰符 返回值 包名.包名.包名...类名.方法名(参数列表)
            标准的表达式写法:
                public void com.jiading.service.impl.AccountServiceImpl.saveAccount()
            访问修饰符可以省略(即那个public)
                void com.jiading.service.impl.AccountServiceImpl.saveAccount()
            返回值可以使用通配符表示任意返回值
                * com.jiading.service.impl.AccountServiceImpl.saveAccount()
            包名可以使用通配符表示任意包表示任意包,有几级包就需要写几个*
                * *.*.*.*.AccountServiceImpl.saveAccount()
            可以使用..表示当前包及其子包
                * *..AccountServiceImpl.saveAccount()
            类名和方法名都可以使用*来实现通配
                * *..*.*()
            参数列表可以直接写数据类型:
                基本类型直接写名称   int
                引用类型写包名.类名的方式   java.lang.String
            类型可以使用通配符表示任意类型,但是必须有参数
            可以使用..表示有无参数均可,有参数可以是任意类型
                * *..*.*(..)
            最终得到的全通配写法:
                * *..*.*(..)

            实际开发中切入点表达式的通常写法:
                切到业务层实现类下的所有方法:
                    * com.jiading.service.impl.*.*(..)

    -->
    <bean class="com.jiading.utils.Logger" id="logger"></bean>
    <aop:config>
        <!-- 配置切面-->
        <aop:aspect id="logAdvice" ref="logger">
            <!-- 配置通知的类型并且建立通知方法和切入点方法的关联-->
            <aop:before method="printLog" pointcut="execution(* com.jiading.service.impl.*.*(..))"></aop:before>
        </aop:aspect>
    </aop:config>
</beans>

实际使用的时候就不需要管AOP了,因为已经在配置文件中配置好了,使用时候创建容器再直接获取对象就好了:

package com.jiading.test;

import com.jiading.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/*
测试AOP的配置
 */
public class AOPTest {
    public static void main(String[] args) {
        //1.获取容器
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.获取对象
        IAccountService as=(IAccountService) ac.getBean("accountService");
        //3.执行方法
        as.saveAccount();
        as.deleteAccount();
    }
}

常用通知类型

bean.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"
       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">

    <bean id="accountService" class="com.jiading.service.impl.AccountServiceImpl"></bean>
    <bean class="com.jiading.utils.Logger" id="logger"></bean>
    <aop:config>
        <aop:pointcut id="accountServicePointCut" expression="execution(* com.jiading.service.impl.*.*(..))"/>
        <!-- 配置切面-->
        <aop:aspect id="logAdvice" ref="logger">
            <!-- 配置通知的类型并且建立通知方法和切入点方法的关联-->
            <aop:before method="beforePrintLog" pointcut-ref="accountServicePointCut"></aop:before>
            <aop:after-returning method="afterReturningPrintLog"
                                 pointcut-ref="accountServicePointCut"></aop:after-returning>
            <!-- 异常通知和后置通知永远只能执行一个-->
            <aop:after-throwing method="afterThrowingPrintLog"
                                pointcut-ref="accountServicePointCut"></aop:after-throwing>
            <!-- 最终通知无论切入点方法是否正常执行都会在后面执行-->
            <aop:after method="afterPrintLog" pointcut-ref="accountServicePointCut"></aop:after>
            <!-- 配置切入点表达式.id属性用于指定表达式的唯一标识,expression属性用于指定表达式内容
            它定义在aop:aspect标签内部,就只能用于当前切面使用。如果有新的切面,需要重新配置
            它还可以写在aop:aspect外部,就变成了所有切面可用。但是要求切入点表达式要在切面之前
            -->
            </aop:aspect>
    </aop:config>
</beans>

还有一种环绕通知:
环绕通知实际上是前面几种通知方法的集成,它提供了在代码中配置通知的方式
在环绕通知方法中传入切入点对象,在切入点执行前后进行配置,就是配置了其他的通知类型。执行时需要先获取参数,再带着参数执行.
先在配置文件中配置

<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="accountService" class="com.jiading.service.impl.AccountServiceImpl"></bean>
    <bean class="com.jiading.utils.Logger" id="logger"></bean>
    <aop:config>
        <aop:pointcut id="accountServicePointCut" expression="execution(* com.jiading.service.impl.*.*(..))"/>
        <!-- 配置切面-->
        <aop:aspect id="logAdvice" ref="logger">
            <!--配置环绕通知-->
            <aop:around method="aroundPrintLog" pointcut-ref="accountServicePointCut"></aop:around>
        </aop:aspect>
    </aop:config>
</beans>

配置通知对象:

package com.jiading.utils;

import org.aspectj.lang.ProceedingJoinPoint;

/*
用于记录日志的工具类,提供了公共代码
 */
public class Logger {
    /*
    前置通知
     */
    public void beforePrintLog() {
        System.out.println("Logger类中的beforePrintLog方法开始记录日志");
/*
    后置通知
     */
    }

    public void afterReturningPrintLog() {
        System.out.println("Logger类中的afterReturningPrintLog方法开始记录日志");
/*
    异常通知
     */
    }

    public void afterThrowingPrintLog() {
        System.out.println("Logger类中的afterThrowingPrintLog方法开始记录日志");
    }

    public void afterPrintLog() {
        System.out.println("Logger类中的afterPrintLog方法开始记录日志");

    }

    /*
    环绕通知
        当配置了环绕通知之后,切入点方法没有执行,而通知方法执行了
        分析:
            通过对比动态代理中的环绕通知代码,发现动态代理中的环绕通知有明确的业务层切入点方法调用,而我们的代码中没有
        解决方法:
            Spring框架为我们提供了一个接口:ProceedingJoinPoint,该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。
            该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用
        spring中的环绕通知是spring框架为我们提供的一种在代码中手动控制增强方法何时执行的方法
     */
    public Object aroundPrintLog(ProceedingJoinPoint pjp) {
        Object rtValue = null;
        try {
            Object[] args = pjp.getArgs();
            System.out.println("前置通知");
            rtValue=pjp.proceed(args);
            System.out.println("后置通知");
            return rtValue;
        } catch (Throwable t) {
            System.out.println("异常通知");
            throw new RuntimeException();
        } finally {
            System.out.println("最终通知");
        }

    }
}

spring基于注解的AOP

我们首先需要修改一下配置文件,注意加入了注解的约束xmlns:context

<?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.jiading"></context:component-scan>
    <!-- 配置spring开启注解AOP的支持-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

在通知类中,我们就可以使用注解了

package com.jiading.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/*
用于记录日志的工具类,提供了公共代码
 */
@Component("logger")
@Aspect//表示当前类是一个切面类
public class Logger {
    @Pointcut("execution(* com.jiading.service.impl.*.*(..))")
    private void pt1() {
    }

    /*
        前置通知
         */
    @Before("pt1()")
    public void beforePrintLog() {
        System.out.println("Logger类中的beforePrintLog方法开始记录日志");
/*
    后置通知
     */
    }

    @AfterReturning("pt1()")
    public void afterReturningPrintLog() {
        System.out.println("Logger类中的afterReturningPrintLog方法开始记录日志");
/*
    异常通知
     */
    }

    @AfterThrowing("pt1()")
    public void afterThrowingPrintLog() {
        System.out.println("Logger类中的afterThrowingPrintLog方法开始记录日志");
    }

    @After("pt1()")
    public void afterPrintLog() {
        System.out.println("Logger类中的afterPrintLog方法开始记录日志");

    }

    @Around("pt1()")
    public Object aroundPrintLog(ProceedingJoinPoint pjp) {
        Object rtValue = null;
        try {
            Object[] args = pjp.getArgs();
            System.out.println("前置通知");
            rtValue=pjp.proceed(args);
            System.out.println("后置通知");
            return rtValue;
        } catch (Throwable t) {
            System.out.println("异常通知");
            throw new RuntimeException();
        } finally {
            System.out.println("最终通知");
        }

    }


}

注意,spring基于注解的AOP存在执行问题,就是最终通知会在异常通知和后置通知之前执行。所以实际使用的时候要考虑到这一点。但是使用环绕通知是没有这个问题的,这个也好理解,因为环绕通知的结构是我们直接写的。

原文地址:https://www.cnblogs.com/jiading/p/12368819.html