AOP實(shí)現(xiàn)原理

AOP(Aspect Orient Programming),我們一般稱為面向方面(切面)編程,作為面向?qū)ο蟮囊环N補(bǔ)充,用于處理系統(tǒng)中分布于各個模塊的橫切關(guān)注點(diǎn),比如事務(wù)管理、日志、緩存等等。

AOP實(shí)現(xiàn)的關(guān)鍵在于AOP框架自動創(chuàng)建的AOP代理,AOP代理主要分為靜態(tài)代理和動態(tài)代理,靜態(tài)代理的代表為AspectJ;而動態(tài)代理則以Spring AOP為代表。

使用AspectJ的編譯時增強(qiáng)實(shí)現(xiàn)AOP

AspectJ是靜態(tài)代理的增強(qiáng),所謂的靜態(tài)代理就是AOP框架會在編譯階段生成AOP代理類,因此也稱為編譯時增強(qiáng)。

舉個實(shí)例的例子來說。首先我們有一個普通的Hello類

public class Hello {
    public void sayHello() {
        System.out.println("hello");
    }
 
    public static void main(String[] args) {
        Hello h = new Hello();
        h.sayHello();
    }
}

使用AspectJ編寫一個Aspect

public aspect TxAspect {
    void around():call(void Hello.sayHello()){
        System.out.println("開始事務(wù) ...");
        proceed();
        System.out.println("事務(wù)結(jié)束 ...");
    }
}

這里模擬了一個事務(wù)的場景,類似于Spring的聲明式事務(wù)。使用AspectJ的編譯器編譯

ajc -d . Hello.java TxAspect.aj

查看一下編譯后的Hello.class

public class Hello {
    public Hello() {
    }
 
    public void sayHello() {
        System.out.println("hello");
    }
 
    public static void main(String[] args) {
        Hello h = new Hello();
        sayHello_aroundBody1$advice(h, TxAspect.aspectOf(), (AroundClosure)null);
    }
}

可以看到,這個類比原來的Hello.java多了一些代碼,這就是AspectJ的靜態(tài)代理,它會在編譯階段將Aspect織入Java字節(jié)碼中, 運(yùn)行的時候就是經(jīng)過增強(qiáng)之后的AOP對象。

public void ajc$around$com_listenzhangbin_aop_TxAspect$1$f54fe983(AroundClosure ajc$aroundClosure) {
        System.out.println("開始事務(wù) ...");
        ajc$around$com_listenzhangbin_aop_TxAspect$1$f54fe983proceed(ajc$aroundClosure);
        System.out.println("事務(wù)結(jié)束 ...");
    }

從Aspect編譯后的class文件可以更明顯的看出執(zhí)行的邏輯。proceed方法就是回調(diào)執(zhí)行被代理類中的方法。

使用Spring AOP

與AspectJ的靜態(tài)代理不同,Spring AOP使用的動態(tài)代理,所謂的動態(tài)代理就是說AOP框架不會去修改字節(jié)碼,而是在內(nèi)存中臨時為方法生成一個AOP對象,這個AOP對象包含了目標(biāo)對象的全部方法,并且在特定的切點(diǎn)做了增強(qiáng)處理,并回調(diào)原對象的方法。

Spring AOP中的動態(tài)代理主要有兩種方式,JDK動態(tài)代理和CGLIB動態(tài)代理。JDK動態(tài)代理通過反射來接收被代理的類,并且要求被代理的類必須實(shí)現(xiàn)一個接口。JDK動態(tài)代理的核心是InvocationHandler接口和Proxy類。

如果目標(biāo)類沒有實(shí)現(xiàn)接口,那么Spring AOP會選擇使用CGLIB來動態(tài)代理目標(biāo)類。CGLIB(Code Generation Library),是一個代碼生成的類庫,可以在運(yùn)行時動態(tài)的生成某個類的子類,注意,CGLIB是通過繼承的方式做的動態(tài)代理,因此如果某個類被標(biāo)記為final,那么它是無法使用CGLIB做動態(tài)代理的。

可以做一個簡單的測試。

定義一個接口

public interface Person {
    String sayHello(String name);
}

實(shí)現(xiàn)類

@Component
public class Chinese implements Person {
 
    @Timer
    @Override
    public String sayHello(String name) {
        System.out.println("-- sayHello() --");
        return name + " hello, AOP";
    }
 
    public void eat(String food) {
        System.out.println("我正在吃:" + food);
    }
 
}

這里的@Timer注解是我自己定義的一個普通注解,用來標(biāo)記Pointcut。

定義Aspect

@Aspect
@Component
public class AdviceTest {
 
    @Pointcut("@annotation(com.listenzhangbin.aop.Timer)")
    public void pointcut() {
    }
 
    @Before("pointcut()")
    public void before() {
        System.out.println("before");
    }
}

運(yùn)行

@SpringBootApplication
@RestController
public class SpringBootDemoApplication {
 
    //這里必須使用Person接口做注入
    @Autowired
    private Person chinese;
 
    @RequestMapping("/test")
    public void test() {
        chinese.sayHello("listen");
        System.out.println(chinese.getClass());
    }
 
    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoApplication.class, args);
    }
}

輸出

before
-- sayHello() --
class com.sun.proxy.$Proxy53

可以看到類型是com.sun.proxy.$Proxy53,也就是前面提到的Proxy類,因此這里Spring AOP使用了JDK的動態(tài)代理。

再來看看不實(shí)現(xiàn)接口的情況,修改Chinese類

@Component
public class Chinese {
 
    @Timer
//    @Override
    public String sayHello(String name) {
        System.out.println("-- sayHello() --");
        return name + " hello, AOP";
    }
 
    public void eat(String food) {
        System.out.println("我正在吃:" + food);
    }
 
}

運(yùn)行

@SpringBootApplication
@RestController
public class SpringBootDemoApplication {
 
    //直接用Chinese類注入
    @Autowired
    private Chinese chinese;
 
    @RequestMapping("/test")
    public void test() {
        chinese.sayHello("listen");
        System.out.println(chinese.getClass());
    }
 
    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoApplication.class, args);
    }
}

輸出

before
-- sayHello() --
class com.listenzhangbin.aop.Chinese$$EnhancerBySpringCGLIB$$56b89168

可以看到類被CGLIB增強(qiáng)了,也就是動態(tài)代理。這里的CGLIB代理就是Spring AOP的代理,這個類也就是所謂的AOP代理,AOP代理類在切點(diǎn)動態(tài)地織入了增強(qiáng)處理。

小結(jié)

AspectJ在編譯時就增強(qiáng)了目標(biāo)對象,Spring AOP的動態(tài)代理則是在每次運(yùn)行時動態(tài)的增強(qiáng),生成AOP代理對象,區(qū)別在于生成AOP代理對象的時機(jī)不同,相對來說AspectJ的靜態(tài)代理方式具有更好的性能,但是AspectJ需要特定的編譯器進(jìn)行處理,而Spring AOP則無需特定的編譯器處理。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容