# AOP的小小補充 - Spring AOP ###### tags: `後端技術分享` --- ## 前情提要 什麼是AOP AOP = Aspect-Oriented programming 以面為導向的程式設計,或稱剖面導向程式設計 ---- To quickly summarize, AOP stands for aspect orientated programming. Essentially, it is a way for adding behavior to existing code without modifying that code. 做個快速總結,AOP即剖面導向程式設計。基本上這是增加額外的功能/code但卻不會修改到原本的code的一種做法。 ---- ![](https://i.imgur.com/n3leiyS.png) ---- ![](https://i.imgur.com/FchoWQ4.png) ---- * 一言以蔽之 ``` 將所有Cross-cutting Concern(橫切關注點),決定PointCut(切入點)的時機, 集中在Aspect(切面)實作完畢、並縫合(Weave)到目標上。 ``` ---- ## 為什麼使用AOP 1. 減少重複的code,降低維護難易度 2. 讓核心邏輯更明顯,提升code的可讀性 3. 使用若太複雜,也有可能讓1,2變成反效果 --- ## 前置作業 * 要引用的maven ``` <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> </dependencies> ``` --- ## AOP使用實例 ### 指定annotation * 建立annotation ``` @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface LogExecutionTime { } ``` ---- * 建立Aspect ``` @Around("@annotation(LogExecutionTime)") public Object logExecutionTime(ProceedingJoinPoint joinPoint) { //執行method Object proceed = joinPoint.proceed(); //將結果回傳 return proceed; } ``` ---- ### 指定method ``` @After("execution(* com.tgfc.tw.service.impl.*.*(..))") public void pointcutAfter(JoinPoint joinPoint){ long start = System.currentTimeMillis(); System.out.println("[After]所有Service的method都會呼叫我" + joinPoint.getSignature()); } ``` --- ## 參考出處 1. [Spring 官網文件](https://www.baeldung.com/spring-aop-annotation) 2. [ITREAD01](https://www.itread01.com/content/1549279801.html) 3. [AOP 觀念與術語](https://openhome.cc/Gossip/SpringGossip/AOPConcept.html)