AOP 面向切面編程詳解
阿新 • • 發佈:2017-08-12
準則 rim 實現 handle 建議 cal ring 模式 ide
引言
對類(class)增強的手段通常分為以下三類
1.繼承 子類通過繼承父類或者實現接口對類進行增強
2.裝飾者模式(Wrapper) 常用於對類的某個方法進行重寫,以實現更強大的功能.常用於場合緩沖流,Struct2中StructRequestWarpper類 實現準則:是你還有你,一切全靠你
3.動態代理 一句話概括:獲取實現了一組接口的類對象 需提供目標對象,增強建議 三大參數 :ClassLoader Class[] interfaces InvocationHandler (調用目標對象的方法時會調用這)
區別與裝飾者模式:裝飾者模式通常是對一個類進行加強,而動態代理是獲取一組接口的方法在對類進行增強
具體實現
package com.atguigu.spring.aop; public interface ArithmeticCalculator { int add(int i, int j); int sub(int i, int j); int mul(int i, int j); int div(int i, int j); }
package com.atguigu.spring.aop; import org.springframework.stereotype.Component; @Component("arithmeticCalculator") public class ArithmeticCalculatorImpl implements ArithmeticCalculator { @Override public int add(int i, int j) { int result = i + j; return result; } @Override public int sub(int i, int j) { int result = i - j; return result; } @Override public int mul(int i, int j) { int result = i * j; return result; } @Override public int div(int i, int j) { int result = i / j; return result; } }
要對Arithmetic 的add,sub,mul,div方法進行增強,添加日誌方法,用到了代理
傳統的做法
package com.atguigu.spring.aop; public class ArithmeticCalculatorLoggingImpl implements ArithmeticCalculator { @Override public int add(int i, int j) { System.out.println("The method add begins with [" + i + "," + j + "]"); int result = i + j; System.out.println("The method add ends with " + result); return result; } @Override public int sub(int i, int j) { System.out.println("The method sub begins with [" + i + "," + j + "]"); int result = i - j; System.out.println("The method sub ends with " + result); return result; } @Override public int mul(int i, int j) { System.out.println("The method mul begins with [" + i + "," + j + "]"); int result = i * j; System.out.println("The method mul ends with " + result); return result; } @Override public int div(int i, int j) { System.out.println("The method div begins with [" + i + "," + j + "]"); int result = i / j; System.out.println("The method div ends with " + result); return result; } }
由以上代碼可以看出,相似重復的代碼太多,要對改類進行重寫成更簡單的類,用到了到動態代理
AOP 面向切面編程詳解