天天看點

SpringBoot中AOP的應用記錄

版權聲明:本文為 testcs_dn(微wx笑) 原創文章,非商用自由轉載-保持署名-注明出處,謝謝。 https://blog.csdn.net/testcs_dn/article/details/80325552

AOP目的: 

面向切面程式設計(aspect-oriented programming,AOP)主要實作的目的是針對業務處理過程中的切面進行提取,諸如日志、事務管理和安全這樣的系統服務,進而使得業務邏輯各部分之間的耦合度降低,提高程式的可重用性,同時提高了開發的效率。

Spring AOP術語:

1.連接配接點(Joinpoint) 

程式執行的某個特定位置:如類某個方法調用前、調用後、方法抛出異常後。一個類或一段程式代碼擁有一些具有邊界性質的特定點,這些點中的特定點就稱為“連接配接點”。Spring僅支援方法的連接配接點,即僅能在方法調用前、方法調用後、方法抛出異常時以及方法調用前後這些程式執行點織入通知。連接配接點由兩個資訊确定:第一是用方法表示的程式執行點;第二是用相對點表示的方位。連接配接點是在應用執行過程中能夠插入切面的一個點。

2.切點(Pointcut) 

AOP通過“切點”定位特定的連接配接點。切點和連接配接點不是一對一的關系,一個切點可以比對多個連接配接點。在Spring中,切點通過org.springframework.aop.Pointcut接口進行描述,它使用類和方法作為連接配接點的查詢條件,Spring AOP的規則解析引擎負責切點所設定的查詢條件,找到對應的連接配接點。其實确切地說,不能稱之為查詢連接配接點,因為連接配接點是方法執行前、執行後等包括方位資訊的具體程式執行點,而切點隻定位到某個方法上,是以如果希望定位到具體連接配接點上,還需要提供方位資訊。

3.通知(Advice) 

切面的工作被稱為通知。是織入到目标類連接配接點上的一段程式代碼。 

Spring切面可以應用5種類型的通知: 

- 前置通知(Before):在目标方法被調用之前調用通知功能; 

-後置通知(After):在目标方法完成之後調用通知,此時不會關心方 法的輸出是什麼; 

-傳回通知(After-returning):在目标方法成功執行之後調用通知; 

-異常通知(After-throwing):在目标方法抛出異常後調用通知; 

-環繞通知(Around):通知包裹了被通知的方法,在被通知的方法調 用之前和調用之後執行自定義的行為。

4.引介(Introduction) 

引入允許我們向現有的類添加新方法或屬性,是一種特殊的通知。這樣,即使一個業務類原本沒有實作某個接口,通過AOP的引介功能,我們可以動态地為該業務類添加接口的實作邏輯,讓業務類成為這個接口的實作類。

5.切面(Aspect) 

切面由切點和通知(引介)組成,它既包括了橫切邏輯的定義,也包括了連接配接點的定義。

6.織入(Weaving) 

織入是把切面應用到目标對象并建立新的代理對象的過程。 

AOP有三種織入的方式: 

a、編譯期:切面在目标類編譯時被織入。這種方式需要特殊的編譯器。AspectJ的織入編譯器就是以這種方式織入切面的。 

b、類加載期:切面在目标類加載到JVM時被織入。這種方式需要特殊的類加載器(ClassLoader),它可以在目标類被引入應用之前增 

強該目标類的位元組碼。AspectJ 5的加載時織入(load-time weaving,LTW)就支援以這種方式織入切面。 

c、運作期:切面在應用運作的某個時刻被織入。一般情況下,在織入切面時,AOP容器會為目标對象動态地建立一個代理對象。Spring 

AOP就是以這種方式織入切面的。

AOP織入的目标/對象:

這個是一個需要注意的問題,并不是任何類都會被織入增強的;

隻有使用 @RestController 注解和 @Controller 注解标記的類才會被織入增強。

有些例子給出了接口的定義,有些例子給出Services的定義,然而那都不是AOP的菜啊!反而誤導讀者。

需要做哪些配置?

對不起!真的不需要配置!

有的文章指出要使用 @EnableAspectJAutoProxy 注解,然而親測真的不需要!

示例代碼:

package com.wanyu.configuration;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class AdviceTest {
	
    @Pointcut("execution(public * com.wanyu.fams.controller.*.*(..))")
    public void pointcut() {
		// 僅用于定義 Pointcut
    }
	
    /**
     * 可以在執行方法之前和之後改變參數和傳回值
     * @param joinPoint用于擷取目标方法相關資訊的參數
     * @return 最終的傳回值
     * @throws Throwable
     */
    @Around("pointcut()")
    public Object processTx(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Around增強:執行方法之前,模拟開始事物");
        Object[] args = joinPoint.getArgs();
        if(args != null && args.length > 0 && args[0].getClass() == String.class) {
            args[0] = "增加的字首" + args[0];
        }
        Object rvt = joinPoint.proceed();
        System.out.println("Around增強:執行方法之後,模拟結束事物");
        if(rvt != null && rvt instanceof Integer) {
            rvt = (Integer)rvt * (Integer)rvt;
        }
        return rvt;
    }

    /**
     * 可以在執行方法之前對目标方法的參數進行判斷
     * 通過抛出一個異常來阻斷目标方法的通路
     * @param joinPoint
     */
    @Before("pointcut()")
    public void authority(JoinPoint joinPoint) {
        System.out.println("Before增強:模拟權限檢查");
        System.out.println("Before增強:被織入增強處理的目标目标方法為:" + joinPoint.getSignature().getName());
        System.out.println("Before增強:目标方法的參數為:" + Arrays.toString(joinPoint.getArgs()));
        joinPoint.getArgs()[0] = "除了Around其他的都是是不可以修改目标方法的參數的";
        System.out.println("joinPoint.getArgs()[0]:"+joinPoint.getArgs()[0]);
        System.out.println("Before增強:目标方法的參數為:" + Arrays.toString(joinPoint.getArgs()));
        System.out.println("Before增強:被織入增強處理的目标對象為:" + joinPoint.getTarget());
    }

    /**
     * 可以在執行方法之後對目标方法的參數進行判斷
     * @param joinPoint
     */
    @After("pointcut()")
    public void release(JoinPoint joinPoint) {
        System.out.println("After增強:模拟方法結束後的釋放資源");
        System.out.println("After增強:被織入增強處理的目标方法為:" + joinPoint.getSignature().getName());
        System.out.println("After增強:目标方法的參數為:" + Arrays.toString(joinPoint.getArgs()));
        System.out.println("After增強:被織入增強處理的目标對象為" + joinPoint.getTarget());
    }
    /**
     * 與After的差別在于AfterReturning隻有在方法執行成功的之後才會被織入,如果After和
     * AfterReturning同時存在于一個檔案中,誰寫在前面誰先運作
     * @param joinPoint
     * @param rvt方法的傳回值
     */
    @AfterReturning(pointcut="execution(public * com.wanyu.fams..*.*(..))", returning="rvt")
    public void log(JoinPoint joinPoint, Object rvt) {
        System.out.println("AfterReturning增強:擷取目标方法的傳回值:" + rvt);
        System.out.println("AfterReturning增強:模拟日志功能");
        System.out.println("AfterReturning增強:獲織入增強的目标方法為:" + joinPoint.getSignature().getName());
        System.out.println("AfterReturning增強:目标方法的參數為:" + Arrays.toString(joinPoint.getArgs()));
        System.out.println("AfterReturning增強:被織入增強處理的目标對象為:" + joinPoint.getTarget());
    }
}           

可以看到 pointcut 的定義:

@Pointcut("execution(public * com.wanyu.fams.controller.*.*(..))")           

與引用:

@After("pointcut()")           

也可以單獨的定義切入點

@AfterReturning(pointcut="execution(public * com.wanyu.fams..*.*(..))", returning="rvt")           

控制台輸出

項目啟動後可能看到以下輸出:

2018-05-15 16:53:27.276  WARN 9587 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.dao.support.DaoSupport.afterPropertiesSet() throws java.lang.IllegalArgumentException,org.springframework.beans.factory.BeanInitializationException] because it is marked as final: Consider using interface-based JDK proxies instead!
2018-05-15 16:53:27.277  INFO 9587 --- [           main] o.s.aop.framework.CglibAopProxy          : Final method [public final void org.springframework.dao.support.DaoSupport.afterPropertiesSet() throws java.lang.IllegalArgumentException,org.springframework.beans.factory.BeanInitializationException] cannot get proxied via CGLIB: Calls to this method will NOT be routed to the target instance and might lead to NPEs against uninitialized fields in the proxy instance.
2018-05-15 16:53:27.299  WARN 9587 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.dao.support.DaoSupport.afterPropertiesSet() throws java.lang.IllegalArgumentException,org.springframework.beans.factory.BeanInitializationException] because it is marked as final: Consider using interface-based JDK proxies instead!
2018-05-15 16:53:27.299  INFO 9587 --- [           main] o.s.aop.framework.CglibAopProxy          : Final method [public final void org.springframework.dao.support.DaoSupport.afterPropertiesSet() throws java.lang.IllegalArgumentException,org.springframework.beans.factory.BeanInitializationException] cannot get proxied via CGLIB: Calls to this method will NOT be routed to the target instance and might lead to NPEs against uninitialized fields in the proxy instance.
2018-05-15 16:53:27.318  WARN 9587 --- [           main] o.s.aop.framework.CglibAopProxy          : Unable to proxy interface-implementing method [public final void org.springframework.dao.support.DaoSupport.afterPropertiesSet() throws java.lang.IllegalArgumentException,org.springframework.beans.factory.BeanInitializationException] because it is marked as final: Consider using interface-based JDK proxies instead!           

通路網頁,可能看到以下輸出:

Around增強:執行方法之後,模拟結束事物
After增強:模拟方法結束後的釋放資源
After增強:被織入增強處理的目标方法為:welcome
After增強:目标方法的參數為:[除了Around其他的都是是不可以修改目标方法的參數的]
After增強:被織入增強處理的目标對象為com.wanyu.fams.controller.AdminController@ef6be2
AfterReturning增強:擷取目标方法的傳回值:admin/welcome
AfterReturning增強:模拟日志功能
AfterReturning增強:獲織入增強的目标方法為:welcome
AfterReturning增強:目标方法的參數為:[除了Around其他的都是是不可以修改目标方法的參數的]
AfterReturning增強:被織入增強處理的目标對象為:com.wanyu.fams.controller.AdminController@ef6be2           

織入時機

從控制台輸出來看,它是在 Filter init 之後,

在攔截器注冊之前織入的。

實作AOP的切面主要有以下幾個要素:

  • 使用@Aspect注解将一個java類定義為切面類
  • 使用@Pointcut定義一個切入點,可以是一個規則表達式,比如下例中某個package下的所有函數,也可以是一個注解等。
  • 根據需要在切入點不同位置的切入内容,5種類型的通知 
    • 使用@Before在切入點開始處切入内容
    • 使用@After在切入點結尾處切入内容
    • 使用@AfterReturning在切入點return内容之後切入内容(可以用來對處理傳回值做一些加工處理)
    • 使用@Around在切入點前後切入内容,并自己控制何時執行切入點自身的内容
    • 使用@AfterThrowing用來處理當切入内容部分抛出異常之後的處理邏輯