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

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