底层实现_Java AOP的底层实现原理
AOP用于處理系統中分布于各個模塊的橫切關注點,比如事務管理、日志、緩存等。
AOP實現的關鍵,在于AOP框架自動創建的AOP代理,AOP代理主要分為靜態代理和動態代理,靜態代理的代表為AspectJ;而動態代理則以Spring AOP為代表。
靜態代理 AspectJ
AspectJ是什么?
Eclipse AspectJ is a seamless aspect-oriented extension to the Java? programming language. It is Java platform compatible easy to learn and use.
AspectJ是Java的擴展,用于實現面向切面編程。
AspectJ有自己的編輯器ajc,
AspectJ 官網
Eclipse AspectJ?projects.eclipse.orgAspectJ 入門?www.jianshu.com使用AspectJ的編譯時增強,實現AOP。
之前提到,AspectJ是靜態代理的增強。所謂的靜態代理,就是AOP框架會在編譯階段生成AOP代理類,因此也稱為編譯時增強。
它會在編譯階段將Aspect織入Java字節碼中,運行的時候就是經過增強之后的AOP對象。proceed方法就是回調執行被代理類中的方法。
動態代理(Spring AOP)
Spring AOP官方文檔
Core Technologies?docs.spring.io1.與AspectJ的靜態代理不同,Spring AOP使用的是動態代理。所謂的動態代理,就是說AOP框架不會去修改字節碼,而是在內存中臨時為方法生成一個AOP對象,這個AOP對象包含了目標對象的全部方法,并且在特定的切點做了增強處理,并回調原對象的方法。
2.Spring AOP中的動態代理,主要有兩種方式:JDK動態代理和CGLIB動態代理。
JDK動態代理通過“反射”來接收被代理的類,并且要求被代理的類必須實現一個接口。JDK動態代理的核心是InvocationHandler接口和Proxy類。如果目標類沒有實現接口,那么Spring AOP會選擇使用CGLIB來動態代理目標類。
3.CGLIB(Code Generation Library),是一個代碼生成的類庫,可以在運行時動態地生成某個類的子類。注意,CGLIB是通過繼承的方式做的動態代理,因此如果某個類被標記為final,那么它是無法使用CGLIB做動態代理的。
使用動態代理實質上就是調用時攔截對象方法,對方法進行改造、增強!
測試CGlib生成的動態代理
測試類
package com.example.demo.aop;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;@SpringBootApplication @RestController //@EnableAspectJAutoProxy public class SpringBootDemoApplication {// 直接用Chinese類注入@Autowiredprivate Landlord landlord;@RequestMapping("/test")public void test() {landlord.service();System.out.println(landlord.getClass());}public static void main(String[] args) {SpringApplication.run(SpringBootDemoApplication.class, args);} }Landlord類
package com.example.demo.aop;import org.springframework.stereotype.Component;@Component("landlord") public class Landlord {public void service() {// 僅僅只是實現了核心的業務功能System.out.println("簽合同");System.out.println("收房租");} }Broker類
package com.example.demo.aop.aspect;import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component;@Component @Aspect class Broker {@Before("execution(* com.example.demo.aop.Landlord.service())")public void before() {System.out.println("帶租客看房");System.out.println("談價格");}@After("execution(* com.example.demo.aop.Landlord.service())")public void after() {System.out.println("交鑰匙");} }運行結果
帶租客看房 談價格 簽合同 收房租 交鑰匙 class com.example.demo.aop.Landlord$$EnhancerBySpringCGLIB$$1f1c504aSpring AOP就是這么簡單啦?juejin.imJava AOP的底層實現原理 - 健人雄 - 博客園?www.cnblogs.comSpring(4)——面向切面編程(AOP模塊)?www.jianshu.com總結
以上是生活随笔為你收集整理的底层实现_Java AOP的底层实现原理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: treegrid 如何获取getchan
- 下一篇: uuid java 重复_Java中使用