溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java核心庫實現(xiàn)AOP過程

發(fā)布時間:2020-10-02 18:09:16 來源:腳本之家 閱讀:151 作者:返回主頁 弗蘭克的貓 欄目:編程語言

這篇文章是關(guān)于Java的一個疑難雜癥,通過利用Java核心庫實現(xiàn)簡單的AOP方法,并把實例代碼做了分析對照,以下是全部內(nèi)容:

Spring是一個十分火熱開源框架,而AOP(面向切面編程)則是Spring最重要的概念之一,為了更好的理解和學習AOP的思想,使用核心庫來實現(xiàn)一次不失為一個好方法。

首先介紹一下AOP的概念,AOP(Aspect Oriented Programming),即面向切面編程,所謂的面向切面編程,就是從一個橫切面的角度去設(shè)計代碼的思想,傳統(tǒng)的OOP思想是用封裝繼承和多態(tài)構(gòu)造一種縱向的層次關(guān)系,但不適合定義橫向的關(guān)系,而AOP思想則對此進行了很好的補充。

例如日志管理代碼往往橫向的散布在很多對象層次中,但跟它對應的對象的核心功能可以說是毫無關(guān)系,還有很多類似的代碼,如權(quán)限驗證,調(diào)試輸出,事務處理等,也都是如此,這樣的話就不利于代碼的復用和管理了。

這時候AOP技術(shù)就應運而生了,它利用“橫切”技術(shù),深入封裝對象的內(nèi)部,并將那些影響了多個類的公共行為封裝到一個可重用模塊,并將其命名為"Aspect",即切面。所謂"切面",簡單說就是那些與業(yè)務無關(guān),卻為業(yè)務模塊所共同調(diào)用的邏輯或責任封裝起來,便于減少系統(tǒng)的重復代碼,降低模塊之間的耦合度,并有利于后續(xù)的可操作性和可維護性。

那么AOP又是如何實現(xiàn)的呢?

答案是動態(tài)代理(關(guān)于代理會有另外篇章做詳細介紹,這里就不贅述了)。實現(xiàn)動態(tài)代理有兩種方式,一種是JDK動態(tài)代理,一種是CGLib動態(tài)代理。

那么分別使用兩種方式來做一個簡單的栗子。

先設(shè)計一個場景,假設(shè)我們有一個計算接口ICalculator和實現(xiàn)了該接口的計算器類CalculatorImpl。

public interface ICalculator {
 //加法運算
 public int add(int a,int b);
 //減法
 public int subtract(int a,int b);
 //乘法
 public int multiply(int a,int b);
 //除法
 public int devide(int a,int b);
}
public class CalculatorImpl implements ICalculator{
 @Override
 public int add(int a, int b) {
  return a + b;
 }
 @Override
 public int subtract(int a, int b) {
  return a - b;
 }
 @Override
 public int multiply(int a, int b) {
  return a * b;
 }
 @Override
 public int devide(int a, int b) {
  return a / b;
 }
}

如何在不改動原來計算器類內(nèi)部代碼的情況下記錄計算器各個方法使用的總次數(shù)呢?

有了動態(tài)代理后,其實就很簡單了,先創(chuàng)建一個類并實現(xiàn)InvocationHandler接口,覆蓋invoke方法,

public class TestHandler implements InvocationHandler {
 private Object targetObject;
 private int useTimes;
 //綁定委托對象,并返回代理類
 public Object bind(Object targetObject){
  this.targetObject = targetObject;
  return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),targetObject.getClass().getInterfaces(),this);
 }
 @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  //do something
  before();
  Object result = method.invoke(targetObject,args);
  after();
  return result;
 }
 private void before(){
  System.out.println("we can do something before calculate.");
 }
 private void after(){
  useTimes++;
  System.out.println("已使用:"+useTimes+"次");
 }
}

別看代碼好像有點多,其實主要的方法就是invoke方法,里面的Object result = method.invoke(targetObject,args);相當于繼續(xù)用原來的參數(shù)執(zhí)行原來方法。這里的before和after為自定義的函數(shù),可以在目標代碼執(zhí)行前后做一些我們想要做的事情,比如這里的使用次數(shù)統(tǒng)計。

在bind方法里,傳入目標代理對象,并返回一個代理類實例。接下來我們看看如何使用:

public class TestProxy {
 public static void main(String[] args) {
  TestHandler proxy = new TestHandler();
  ICalculator calculator = (ICalculator)proxy.bind(new CalculatorImpl());
  int result = calculator.add(1,2);
  System.out.println("result is:"+result);
  result = calculator.subtract(3,2);
  System.out.println("result is:"+result);
  result = calculator.multiply(4,6);
  System.out.println("result is:"+result);
  result = calculator.devide(6,2);
  System.out.println("result is:"+result);
 }
}

我們先定義一個TestHandler,然后通過bind方法來獲得一個代理實例,之后我們就可以直接使用這個實例了。運行結(jié)果如下:

we can do something before calculate.
已使用:1次
result is:3
we can do something before calculate.
已使用:2次
result is:1
we can do something before calculate.
已使用:3次
result is:24
we can do something before calculate.
已使用:4次
result is:3

這樣我們就實現(xiàn)了不修改CalculatorImpl內(nèi)部代碼的情況下對代碼進行擴展。

接下來用CGLib的方式來實現(xiàn)一次。

先創(chuàng)建一個類來實現(xiàn)MethodInterceptor接口,并覆蓋intercept方法。其他代碼跟使用JDK代理大同小異,僅僅是獲取代理對象的過程有所差異。

public class CGLibProxy implements MethodInterceptor {
 private int useTimes;
 private Object target;

 public Object getInstance(Object target){
  this.target=target;
  Enhancer enhancer =new Enhancer();
  enhancer.setSuperclass(this.target.getClass());
  enhancer.setCallback(this);
  return enhancer.create();
 }
 @Override
 public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
  before();
  Object result = methodProxy.invokeSuper(o,objects);
  after();
  return result;
 }
 private void before(){
  System.out.println("we can do something before calculate.");
 }
 private void after(){
  useTimes++;
  System.out.println("已使用:"+useTimes+"次");
 }
}

測試一下:

public class TestCGLibProxy {
 public static void main(String[] args) {
  CGLibProxy cgLibProxy = new CGLibProxy();
  ICalculator calculator = (ICalculator) cgLibProxy.getInstance(new CalculatorImpl());
  int result = calculator.add(1,2);
  System.out.println("result is:"+result);
  result = calculator.subtract(3,2);
  System.out.println("result is:"+result);
  result = calculator.multiply(4,6);
  System.out.println("result is:"+result);
  result = calculator.devide(6,2);
  System.out.println("result is:"+result);
 }
}

運行結(jié)果如下:

we can do something before calculate.
已使用:1次
result is:3
we can do something before calculate.
已使用:2次
result is:1
we can do something before calculate.
已使用:3次
result is:24
we can do something before calculate.
已使用:4次
result is:3

現(xiàn)在我們得到了同樣的結(jié)果。(需要導入兩個包,cglib-2.2.2.jar asm-3.3.jar)

兩種方法各有所長,JDK代理需要先設(shè)置一個接口,然后才能實現(xiàn)代理,這是它的缺點,也是它的優(yōu)點,缺點是這樣會麻煩一點,而且無法對那些已經(jīng)封裝好的,沒有實現(xiàn)接口的類進行代理,而CGLib代理的方式不需要使用接口。但也正是因為如此,JDK代理的方式僅僅攔截類中覆蓋接口的方法,而CGLib則會攔截類的所有方法調(diào)用。兩者各有利弊,所以需要具體情況具體分析。在Spring中也是混雜使用了兩種代理模式。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI