Spring AOP學習
文章目錄
- Spring AOP學習
-
- 什麼是Spring AOP
- Spring AOP解決什麼問題
- 在Spring Boot實作AOP
- 相關知識點
- 相關概念
- Spring切面的5種類型通知
- 總結
- 參考資料
Spring AOP建構在動态代理的基礎之上,是以僅支援方法級别的連接配接點,如果需要更細粒度的攔截可以使用Aspect
什麼是Spring AOP
來自百度百科
在軟體業,AOP為Aspect Oriented Programming的縮寫,意為:面向切面程式設計,通過預編譯方式和運作期動态代理實作程式功能的統一維護的一種技術。AOP是OOP的延續,是軟體開發中的一個熱點,也是Spring架構中的一個重要内容,是函數式程式設計的一種衍生範型。利用AOP可以對業務邏輯的各個部分進行隔離,進而使得業務邏輯各部分之間的耦合度降低,提高程式的可重用性,同時提高了開發的效率。
Spring AOP解決什麼問題
日志、安全審計等在整個程式流程會多處使用,但是跟業務又沒什麼關系,像這類問題就可以用AOP來實作,将核心業務和非業務代碼解耦
在Spring Boot實作AOP
Spring Boot中添加spring-boot-starter-aop的依賴;Sprig Boot中已經預設啟用aop功能了,非Spring Boot的需要配置啟用aop
實作的是一個到學校圖書館看書的場景,不管到圖書館裡面看書還是自習,進出都需要刷學生卡,那麼這部分業務就可以作為一個切面處理
libraryAspect.Java
package com.ccccye.springstudy.S20190727;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* Created by ccccye on 2019/7/27
* 圖書館-切面
*/
@Aspect
@Component
public class libraryAspect {
/**
* 可重用的切點
*/
@Pointcut("execution(* com.ccccye.springstudy.S20190727.LibraryController.*(..))")
public void libraryCut(){ }
/**
* 前置通知
*/
//@Before("execution(* com.ccccye.springstudy.S20190727.LibraryController.*(..))")
@Before("libraryCut()")
public void before(){
System.out.printf("滴,學生卡 進入圖書館\r\n");
}
/**
* 後置通知
*/
//@After("execution(* com.ccccye.springstudy.S20190727.LibraryController.*(..))")
@After("libraryCut()")
public void after(){
System.out.printf("滴,學生卡 離開圖書館\r\n");
}
/**
* 後置通知-異常之後
*/
@AfterThrowing("libraryCut()")
public void afterThrowing(){
System.out.printf("哎呀,在圖書館大聲吵鬧被趕出來了\r\n");
}
}
LibraryController.Java
package com.ccccye.springstudy.S20190727;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by ccccye on 2019/7/27
* 圖書館接口
*/
@RestController
@RequestMapping("/library/")
public class LibraryController {
@RequestMapping(value = "read")
public String readBook() throws Exception{
// if (1==1){
// throw new Exception("大聲吵鬧");
// }
String msg = "周末看書ing\r\n";
System.out.printf(msg);
return msg;
}
}
具體的實作項目可以到我的GitHub下載下傳
相關知識點
- JAVA設計模式-代理模式
相關概念
- Aspect(切面),Aspect聲明類似于JAVA中的類聲明,在Aspect中包含着一些PointCut以及相應的Advice
- Joint point(連接配接點),表示在程式中明确定義的點,典型的包括方法調用,對類成員的通路以及異常處理程式塊的執行等等,它自身還可以嵌套其它 joint point
- Pointcut(切點),表示一組 joint point,這些 joint point 或是通過邏輯關系組合起來,或是通過通配、正規表達式等方式集中起來,它定義了相應的 Advice 将要發生的地方
- Advice(通知),Advice 定義了在 Pointcut 裡面定義的程式點具體要做的操作,它通過 before、after 和 around 來差別是在每個 joint point 之前、之後還是代替執行的代碼
- Target(目标對象),織入 Advice 的目标對象
- Weaving(織入),将 Aspect 和其他對象連接配接起來, 并建立 Adviced object 的過程
Spring切面的5種類型通知
- Before(前置通知),在目标方法調用之前調用通知功能
- After(後置通知),在目标方法完成之後調用通知,此時不會關心方法輸出的是什麼
- After-Returning(傳回通知),在目标方法成功執行之後調用通知
- After-Throwing(異常通知),在目标方法抛出異常後調用通知
- Around(環繞通知),通知包裹了被通知的方法,在被通知之前和通知之後執行自定義的行為
總結
通過學習Spring AOP,以後遇到公共的非核心業務,就會馬上想到用AOP實作。
參考資料
- Spring實戰(第4版)
- 細說Spring——AOP詳解(AOP概覽)