spring03-aop之xml配置, 前置通知,后置通知,异常通知,最终通知,环绕通知

接上一讲 第三方的动态代理:

package com.hr.cglib;

import com.hr.proxy.IProducer;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 模拟一个消费者
 */
public class Client {

    public static void main(String[] args) {
        final Producer producer = new Producer();

        /**
         * 动态代理:
         *  特点: 字节码随用随创建,随用随加载
         *  作用: 不修改源码的基础上对方法增强
         *  分类:
         *      基于接口的动态代理
         *      基于子类的动态代理
         *   基于子类的动态代理:
         *    涉及的类:Enhancer
         *    提供者:cglib 第三方
         *   创建代理对象:
         *      Enhancer类中的create方法是
         *   创建代理对象的要求:
         *      被代理类不能是最终类
         *   newProxyInstance方法的参数:
         *          Class: 字节码
         *              被代理对象的字节码
         *
         *          Callback: 用于提供增强的代码
         *              我们一般写的都是该接口的子接口实现类,MethodInterceptor
         *
         *
         */
        Producer cglibProducer = (Producer) Enhancer.create(Producer.class, new MethodInterceptor() {
            /**
             * 执行被代理对象的任何方法都会经过该方法
             * @param proxy
             * @param method
             * @param args
             *   以上三个参数和基于接口的动态代理中invoke方法的参数是一样的,
             * @param methodProxy
             * @return
             * @throws Throwable
             */
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                //提供增强的代码
                Object returnValue = null;
                //1 获取方法执行的参数
                Float money = (Float) args[0];
                //2 判断当前方法是不是 销售方法
                if ("saleProduct".equals(method.getName())) {
                    //执行方法
                    returnValue = method.invoke(producer, money * 0.8f);
                }
                return returnValue;
            }
        });

        cglibProducer.saleProduct(12000f);
    }
}

新建一个maven项目, 导入座标: 

 <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>
    </dependencies>

编写业务类接口和代码:  业务类中的三个方法是连接点,也是切入点,连接点包含切入点, 因为三个方法都需要打印日志(增强),

所以都是要被增强的切入点

package com.hr.service.impl;

import com.hr.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;
    }
}

日志类:

package com.hr.service.utils;

/**
 * 日志工具类
 */
public class Logger {
    /**
     * 打印日志, 计划让其在切入点方法执行之前执行(切入点方法就是要被增强的业务层方法)
     */
    public void printLog() {
        System.out.println("Logger类中的printLog方法开始记录日志了");
    }
}

spring的xml配置.  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.hr.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(表达式)
                表达式:
                    (访问修饰符 可以不写) 返回值 包名.包名.包名...类名.方法名(参数列表)
                    全通配写法: * *..*.*(..)
                  实际开发中,切入点表达式的通常写法:
                    切到业务类实现类下的所有方法:
                        * com.hr.service.impl.*.*(..)

       -->

    <bean id="logger" class="com.hr.service.utils.Logger"></bean>

    <aop:config>
        <aop:aspect id="logAdvice" ref="logger">
            <aop:before method="printLog" pointcut="execution(* com.hr.service.impl.*.*(..))"></aop:before>
        </aop:aspect>
    </aop:config>

</beans>

配置了前置通知, 测试类和打印结果:

 

加上前置通知, 后置通知,异常通知,最终通知

 

配置环绕通知:

Logger类中的环绕通知代码

package com.hr.service.utils;

import org.aspectj.lang.ProceedingJoinPoint;

/**
 * 日志工具类
 */
public class Logger {

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

    /**
     * 打印日志, 计划让其在切入点方法执行之前执行(切入点方法就是要被增强的业务层方法)
     * 前置通知
     */
    public void beforPrintLog() {
        System.out.println("前置通知Logger类中的beforPrintLog方法开始记录日志了");
    }

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

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

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

    /**
     * 环绕通知
     * 问题:
     *  当配置了环绕通知之后,切入点方法没有执行,而通知方法执行了
     * 分析:
     *  通过对比动态代理中环绕通知的代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码没有
     *  解决:
     *      Spring框架为我们提供了一个接口,ProceedingJoinPoint, 该接口有一个方法proceed(),此方法就相当于明确调用切入点方法
     *      该接口可以作为环绕通知的方法参数, 在程序执行时,spring会为我们提供该接口的实现类供我们使用
     * spring环绕通知作用:
     *      它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式
     */
    public Object aroundPrintLog(ProceedingJoinPoint pjp) {
        Object rtValue = null;
        try {
            Object[] args = pjp.getArgs();

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

            rtValue = pjp.proceed(args);   //明确调用业务层方法(切入点方法)

            System.out.println("Logger类中的aroundPrintLog方法开始记录日志了... 后置");
            return rtValue;
        } catch (Throwable throwable) {
            System.out.println("Logger类中的aroundPrintLog方法开始记录日志了... 异常");
            throw new RuntimeException(throwable);
        }finally {
            System.out.println("Logger类中的aroundPrintLog方法开始记录日志了... 最终");
        }

    }


}

 

github:  https://github.com/2402zmybie/spring03_springAop

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章