手动实现SPring中的AOP(2)
生活随笔
收集整理的這篇文章主要介紹了
手动实现SPring中的AOP(2)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
相關名詞的解釋:通知定義了要織入目標對象的邏輯,以及執行時機。
Spring 中對應了 5 種不同類型的通知:
· 前置通知(Before):在目標方法執行前,執行通知
· 后置通知(After):在目標方法執行后,執行通知,此時不關系目標方法返回的結果是什么
· 返回通知(After-returning):在目標方法執行后,執行通知
· 異常通知(After-throwing):在目標方法拋出異常后執行通知
· 環繞通知(Around): 目標方法被通知包裹,通知在目標方法執行前和執行后都被會調用
定義一個包含切面邏輯的對象,這里假設叫 logMethodInvocation 定義一個 Advice 對象(實現了 InvocationHandler 接口),并將上面的 logMethodInvocation 和 目標對象傳入 將上面的 Adivce 對象和目標對象傳給 JDK 動態代理方法,為目標對象生成代理
Spring 中對應了 5 種不同類型的通知:
· 前置通知(Before):在目標方法執行前,執行通知
· 后置通知(After):在目標方法執行后,執行通知,此時不關系目標方法返回的結果是什么
· 返回通知(After-returning):在目標方法執行后,執行通知
· 異常通知(After-throwing):在目標方法拋出異常后執行通知
· 環繞通知(Around): 目標方法被通知包裹,通知在目標方法執行前和執行后都被會調用
切點(Pointcut):如果說通知定義了在何時執行通知,那么切點就定義了在何處執行通知。所以切點的作用就是通過匹配規則查找合適的連接點(Joinpoint),AOP 會在這些連接點上織入通知。
?切面(Aspect):切面包含了通知和切點,通知和切點共同定義了切面是什么,在何時,何處執行切面邏輯。
實現步驟:
?
?
MethodInvocation 接口 // 實現類包含了切面邏輯,如上面的 logMethodInvocation Advice 接口 // 繼承了 InvocationHandler 接口 BeforeAdvice 類 // 實現了 Advice 接口,是一個前置通知 SimpleAOP 類 // 生成代理類 SimpleAOPTest // SimpleAOP 從測試類 HelloService 接口 // 目標對象接口 HelloServiceImpl // 目標對象MethodInvocation 接口代碼:
public interface MethodInvocation {void invoke(); }?Advice 接口代碼:
public interface Advice extends InvocationHandler {}BeforeAdvice 實現代碼:
public class BeforeAdvice implements Advice {private Object bean;private MethodInvocation methodInvocation;public BeforeAdvice(Object bean, MethodInvocation methodInvocation) {this.bean = bean;this.methodInvocation = methodInvocation;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// 在目標方法執行前調用通知methodInvocation.invoke();return method.invoke(bean, args);} }SimpleAOP 實現代碼:
public class SimpleAOP {public static Object getProxy(Object bean, Advice advice) {return Proxy.newProxyInstance(SimpleAOP.class.getClassLoader(), bean.getClass().getInterfaces(), advice);} }HelloService 接口,及其實現類代碼:
public interface HelloService {void sayHelloWorld(); }public class HelloServiceImpl implements HelloService {@Overridepublic void sayHelloWorld() {System.out.println("hello world!");} }SimpleAOPTest 代碼:
public class SimpleAOPTest {@Testpublic void getProxy() throws Exception {// 1. 創建一個 MethodInvocation 實現類MethodInvocation logTask = () -> System.out.println("log task start");HelloServiceImpl helloServiceImpl = new HelloServiceImpl();// 2. 創建一個 AdviceAdvice beforeAdvice = new BeforeAdvice(helloServiceImpl, logTask);// 3. 為目標對象生成代理HelloService helloServiceImplProxy = (HelloService) SimpleAOP.getProxy(helloServiceImpl,beforeAdvice);helloServiceImplProxy.sayHelloWorld();} }?
轉載于:https://www.cnblogs.com/BaoZiY/p/11375859.html
總結
以上是生活随笔為你收集整理的手动实现SPring中的AOP(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手动实现SPring中的AOP(1)
- 下一篇: 构造、拷贝构造、赋值、析构