Spring AOP---切面編程基礎(動態代理)


Spring AOP---切面編程基礎(動態代理)


目標對象target:要被代理的對象

 

 

連接點:連接被代理對象中所有的方法.

 

 

切入點:被代理對象中指定要增強的方法

 

 

通知:通知對切入點做的具體操作叫做通知

 

 

切面:切入點+通知

 

 

織入:從被代理對象到代理對象的過程叫織入

 

 

代理:一個類被AOP增強後產生的對象


Spring aop底層實現的兩種(jdk(必須實現接口的動態代理)cglib(即可實現接口,也可以不實現))

AOP分爲靜態AOP和動態AOP。靜態AOP是指AspectJ實現的AOP,他是將切面代碼直接編譯到Java類文件中。動態AOP是指將切面代碼進行動態織入實現的AOPSpringAOP爲動態AOP,實現的技術爲: JDK提供的動態代理技術  CGLIB(動態字節碼增強技術


Jdk的動態代理

在運行時,通過jvm內部動態的通過類加載器來生成class字節碼對象實現,jdk動態代理,只針對於接口操作.

 

//創始一個使用jdkproxy完成動態代理工具

publicclass JDKProxyFactory implements InvocationHandler {

 

       private Object target;

       public JDKProxyFactory(Object target) {

              this.target = target;

       }

       // 創建代理對象

       public Object createProxy() {

 

              // 使用Proxy完成代理對象創建

              // 1.得到目標對象的ClassLoader

              ClassLoader loader =target.getClass().getClassLoader();

              // 2.得到目標對象的實現接口的Class[]

              Class[] interfaces =target.getClass().getInterfaces();

              // 3.第三個參數需要一個實現了InvocationHandler接口的對象

              returnProxy.newProxyInstance(loader, interfaces, this);

       }

       // 在代理實例上處理方法調用並返回結果。

       // 參數1 就是代理對象,一般不使用

       // 參數2它調用的方法的Method對象

       // 參數3調用的方法的參數

       @Override

       public Object invoke(Object proxy, Methodmethod, Object[] args) throws Throwable {

 

              // 功能增強操作

              System.out.println("日誌操作....");

 

              return method.invoke(target,args);

       }

}


 

Cglib動態代理

個人覺得和proxy的方式類似

//1,創建enhance對象

Enhancer enhancer = newEnhancer();

//2,相當於是反射該類

enhancer.setSuperclass(target.getClass());

//設置回調函數,相當於InvocationHandler,中的inoke方法enhancer.setCallback(this);

 

實現了MethodInterceptor接口

使用其中的intercept方法返回一個方法





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