微信公眾號:compassblog
歡迎關注、轉發,互相學習,共同進步!
有任何問題,請後臺留言聯絡!
1、AOP概述
(1)、什麼是 AOP
AOP 為 Aspect Oriented Programming 的縮寫,意為“面向切面程式設計”。AOP 是 OOP (物件導向)的延續,可以對業務的各個部分進行隔離,從而使得業務邏輯各部分之間的耦合度降低,提高程式的可重用性和開發效率。
(2)、AOP 思想圖解:橫向重複,縱向切取
過濾器
攔截器
事務管理
(3)、AOP 可以實現的功能
許可權驗證
日誌記錄
效能控制
事務控制
(4)、AOP 底層實現的兩種代理機制
JDK的動態代理 :針對實現了介面的類產生代理
Cglib的動態代理 :針對沒有實現介面的類產生代理,應用的是底層的位元組碼增強的技術生成當前類的子類物件
2、Spring底層AOP實現原理
(1)、 JDK 動態代理增強一個類中方法:被代理物件必須要實現介面,才能產生代理物件。如果沒有介面將不能使用動態代理技術。
public class MyJDKProxy implements InvocationHandler {
private UserDao userDao;
public MyJDKProxy(UserDao userDao) {
this.userDao = userDao;
}
public UserDao createProxy(){
UserDao userDaoProxy = (UserDao)Proxy.newProxyInstance(userDao.getClass().getClassLoader(),userDao.getClass().getInterfaces(), this);
return userDaoProxy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
if("save".equals(method.getName())){
System.out.println("許可權校驗=============
}
return method.invoke(userDao, args);
}
}
複製程式碼
(2)、Cglib 動態代理增強一個類中的方法:可以對任何類生成代理,代理的原理是對目標物件進行繼承代理。如果目標物件被final修飾,那麼該類無法被cglib代理。
public class MyCglibProxy implements MethodInterceptor{
private CustomerDao customerDao;
public MyCglibProxy(CustomerDao customerDao){
this.customerDao = customerDao;
}
// 生成代理的方法:
public CustomerDao createProxy(){
// 建立Cglib的核心類:
Enhancer enhancer = new Enhancer();
// 設定父類:
enhancer.setSuperclass(CustomerDao.class);
// 設定回撥:
enhancer.setCallback(this);
// 生成代理:
CustomerDao customerDaoProxy = (CustomerDao) enhancer.create();
return customerDaoProxy;
}
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
if("delete".equals(method.getName())){
Object obj = methodProxy.invokeSuper(proxy, args);
System.out.println("日誌記錄================");
return obj;
}
return methodProxy.invokeSuper(proxy, args);
}
}
複製程式碼
3、Spring 基於 AspectJ AOP 開發的相關術語
Joinpoint(連線點):所謂連線點是指那些被攔截到的點。在 spring 中,這些點指的是方法,因為 spring 只支援方法型別的連線點
Pointcut(切入點):所謂切入點是指我們要對哪些 Joinpoint 進行攔截的定義
Advice(通知/增強):所謂通知是指攔截到 Joinpoint 之後所要做的事情就是通知,通知分為前置通知,後置通知,異常通知,最終通知,環繞通知(切面要完成的功能)
Introduction(引介):引介是一種特殊的通知,在不修改類程式碼的前提下, Introduction 可以在執行期為類動態地新增一些方法或 Field
Target(目標物件):代理的目標物件
Weaving(織入):是指把增強應用到目標物件來建立新的代理物件的過程。spring 採用動態代理織入,而 AspectJ 採用編譯期織入和類裝在期織入
Proxy(代理):一個類被 AOP 織入增強後,就產生一個結果代理類
Aspect(切面):是切入點和通知(引介)的結合
您可能還喜歡:
本系列後期仍會持續更新,歡迎關注!
如果你認為這篇文章有用,歡迎轉發分享給你的好友!
本號文章可以任意轉載,轉載請註明出處!
掃描關注微信公眾號,瞭解更多