Spring深入学习(10)AOP(面向切面编程)中的通知xml配置以及注解配置

四种常用通知的xml配置

在Logger类中添加四种通知需要打印的日志

package com.tianqicode.utils;

/**
 * 用于打印日志的工具类,里面提供了公共的代码
 */
public class Logger {

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

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

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

    /**
     * 最终通知
     */
    public void afterPrintLog() {
        System.out.println("最终通知Logger类中的beforePrintLog方法开始记录日志了。");
    }
}

在配置文件添加四种通知的配置

<aop:config>
        <aop:aspect id="logAdvice" ref="logger">
            <!-- 前置通知:在切入点之前执行 -->
            <aop:before method="beforePrintLog" pointcut="execution(* com.tianqicode.service.Impl.*.*(..))"></aop:before>
            <!-- 后置通知:在切入点正常执行之后执行,与异常通知只能执行一个 -->
            <aop:after-returning method="afterReturnPrintLog" pointcut="execution(* com.tianqicode.service.Impl.*.*(..))"></aop:after-returning>
            <!-- 异常通知:在切入点产生异常时执行,与后置通知只能执行一个 -->
            <aop:after-throwing method="afterThrowingPrintLog" pointcut="execution(* com.tianqicode.service.Impl.*.*(..))"></aop:after-throwing>
            <!-- 最终通知:配置最终通知,不论切入点方法是否正常执行都会执行 -->
            <aop:after method="afterPrintLog" pointcut="execution(* com.tianqicode.service.Impl.*.*(..))"></aop:after>
        </aop:aspect>
    </aop:config>

在测试类中再次正常执行业务类中的方法,发现除了异常通知之外都正常执行了。在业务类中添加异常语句发现除了后置通知以及切入点方法之外都正常执行了。

添加aop:pointcut 标签简化通知配置

<aop:config>
        <aop:aspect id="logAdvice" ref="logger">
            <!-- 前置通知:在切入点之前执行 -->
            <aop:before method="beforePrintLog" pointcut-ref="pointcut"></aop:before>
            <!-- 后置通知:在切入点正常执行之后执行,与异常通知只能执行一个 -->
            <aop:after-returning method="afterReturnPrintLog" pointcut-ref="pointcut"></aop:after-returning>
            <!-- 异常通知:在切入点产生异常时执行,与后置通知只能执行一个 -->
            <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pointcut"></aop:after-throwing>
            <!-- 最终通知:配置最终通知,不论切入点方法是否正常执行都会执行 -->
            <aop:after method="afterPrintLog" pointcut-ref="pointcut"></aop:after>

            <!-- 配置切点表达式:id属性用于表达式的唯一标识。expression属性用于执行表达式内容
            	此标签写在aop:aspect标签内只能当前切面使用。
            	它还可以写在标签外,此时就变成了所有切面可用。
            	但是约束规定,只能出现在aop:aspect标签的前面
             -->
            <aop:pointcut id="pointcut" expression="execution(* com.tianqicode.service.Impl.*.*(..))"/>
        </aop:aspect>
    </aop:config>
spring中的环绕通知xml配置

这时候我们将之前配置的通知全部注释掉,在下面添加环绕通知的配置

<aop:around method="aroundPrintLog" pointcut-ref="pointcut"></aop:around>

在日志工具类里添加环绕通知的方法

public void aroundPrintLog() {
        System.out.println("aroundPrintLog方法开始记录日志了。");
    }

现在运行测试类观察运行结果,我们期待的结果应该是日志打印,以及业务类运行,但是控制台只打印了日志并没有运行业务类,接下来分析并解决问题

/**
     * 环绕通知
     * 问题:
     *     当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了。
     * 分析:
     *      通过对比动态代理中的环绕通知代码,我们发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有
     * 解决:
     *      Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于我们
     *      明确调用切入点方法。
     *      该接口可以作为环绕通知的方法参数,在执行程序时,spring框架会为我们提供该接口的实现类供我们使用
     */

通过以上的分析,我们只需要在环绕通知中调用切点方法就可以了

public Object aroundPrintLog(ProceedingJoinPoint joinPoint) {

        try {

            Object returnValue = null;
            Object args[] = joinPoint.getArgs();//通过getArgs()得到方法执行所需参数
            System.out.println("aroundPrintLog方法开始记录日志了。。前置");
            returnValue = joinPoint.proceed(args);//明确调用业务类方法
            System.out.println("aroundPrintLog方法开始记录日志了。。后置");

            return returnValue;

        } catch (Throwable throwable) {
            System.out.println("aroundPrintLog方法开始记录日志了。。异常");
            throw  new RuntimeException(throwable);
        }finally {
            System.out.println("aroundPrintLog方法开始记录日志了。。最终");
        }

    }

其实环绕通知就是spring提供给我们的一种手动控制通知或者代码增强执行的方式,如果需要前置通知就将需要打印的日志写在切点方法之前,同理后置通知就写在切点方法之后。异常通知写在catch代码块中,最终通知写在finally代码块中。

四种常用通知的注解配置方式

首先添加相应的约束以及创建容器时要扫描的包的配置

<?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">

添加创建容器需要扫描的包
之前配置bean对象的标签就可以全部删掉了

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

添加配置spring开启注解AOP的支持

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

在业务类上添加注解

@Service("accountService")

在日志工具类上添加注解,以及日志工具类中的各个通知方法的注解

package com.tianqicode.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.tianqicode.service.Impl.*.*(..))")//指定切入点表达式
    private void pt1(){
    }
    /**
     * 前置通知
     */
    @Before("pt1()")
    public void beforePrintLog() {
        System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。");
    }

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

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

    /**
     * 最终通知
     */
    @After("pt1()")
    public void afterPrintLog() {
        System.out.println("最终通知Logger类中的beforePrintLog方法开始记录日志了。");
    }

    /**
     * 环绕通知
     * 问题:
     *     当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了。
     * 分析:
     *      通过对比动态代理中的环绕通知代码,我们发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有
     * 解决:
     *      Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于我们
     *      明确调用切入点方法。
     *      该接口可以作为环绕通知的方法参数,在执行程序时,spring框架会为我们提供该接口的实现类供我们使用
     */

    @Around("pt1()")
    public Object aroundPrintLog(ProceedingJoinPoint joinPoint) {

        try {

            Object returnValue = null;
            Object args[] = joinPoint.getArgs();//得到方法执行所需参数

            System.out.println("aroundPrintLog方法开始记录日志了。。前置");

            returnValue = joinPoint.proceed(args);//明确调用业务类方法


            System.out.println("aroundPrintLog方法开始记录日志了。。后置");

            return returnValue;


        } catch (Throwable throwable) {
            System.out.println("aroundPrintLog方法开始记录日志了。。异常");
            throw  new RuntimeException(throwable);
        }finally {
            System.out.println("aroundPrintLog方法开始记录日志了。。最终");
        }

    }
}

由于调用四种通知方法与调用环绕方法内容重复,所以在测试分开的通知方法时将环绕通知的注解给注释掉。点击运行,发现控制台输出的顺序有些问题。后置方法在最终方法后被调用。这是spring自己的问题,与我无关。

前置通知Logger类中的beforePrintLog方法开始记录日志了。
查找账户成功
最终通知Logger类中的beforePrintLog方法开始记录日志了。
后置通知Logger类中的beforePrintLog方法开始记录日志了。

Process finished with exit code 0

现在测试环绕通知方法,将分开的通知方法注解注释掉
点击运行

aroundPrintLog方法开始记录日志了。。前置
查找账户成功
aroundPrintLog方法开始记录日志了。。后置
aroundPrintLog方法开始记录日志了。。最终

Process finished with exit code 0

完全没有任何问题
以后尽量不要使用spring自动调用通知方法

发布了30 篇原创文章 · 获赞 2 · 访问量 627

猜你喜欢

转载自blog.csdn.net/qq_43585377/article/details/102689832
今日推荐