您的位置:首頁技術文章
文章詳情頁

spring項目中切面及AOP的使用方法

瀏覽:3日期:2023-07-06 08:25:17
使用AOP的原因(AOP簡介)

我們知道,spring兩大核心,IOC(控制反轉)和AOP(切面),那為什么要使用AOP,AOP是什么呢,嚴格來說,AOP是一種編程規范,是一種編程思想,并非spring創造,AOP可以幫助我們在一定程度上從冗余的通用的業務邏輯中解脫出來,最明顯的,比如每個接口的請求,都要記錄日志,那這個操作如果每個地方都寫,就會很繁瑣,當然,記錄日志并不是唯一的用法

spring的AOP只能基于IOC來管理,它只能作用于spring容器的bean

并且,spring的AOP為的是解決企業開發中出現最普遍的方法織入,并不是為了像AspectJ那樣,成為一個完全的AOP使用解決方案

AOP的使用

開啟AOP支持

要使用AOP,首先要開啟AOP的支持

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId></dependency>

啟動類添加 @EnableAspectJAutoProxy 注解

編寫切面類與測試方法

@Aspect@Componentpublic class MyAop { }

@RestControllerpublic class OneController { @GetMapping('/doCheck') public String doCheck (int age) {System.out.println('doCheck');if (age > 1) {throw new MyException(ExceptionEnu.SUCCESS);} else { throw new MyException(ExceptionEnu.FAILD);} } }

記得切面類交給spring管理哦~ @Component

編寫切面方法

@Before

這個注解的用法呢,就是說,在執行你要執行的東西之前,執行加了這個注解的方法

比如

@Before(value = 'execution (* own.study.web.OneController.*(..))') public void doAop( ) {System.out.println('before aop'); }

也就是說,如果我要調用 OneController 的方法,在調用到之前,會執行這個 doAop 方法

讓我們來測試一下

spring項目中切面及AOP的使用方法

@After

這個注解的用法,就是說,當你執行完你的方法之后,真的返回給調用方之前,執行加了這個注解的方法

比如

@After(value = 'execution (* own.study.web.OneController.*(..))') public void doAfter() {System.out.println('after aop'); }

讓我們來測試一下

spring項目中切面及AOP的使用方法

@AfterThrowing

見名知意,在發生異常后,執行加了此注解的方法

注意我上面寫的測試方法了嗎?我拋出了自定義的異常

讓我們測試一下

spring項目中切面及AOP的使用方法

@AfterReturning

這個注解的用法也是看名字就能猜到,執行完后,執行此方法

但是!這個執行完,指的是正常執行完,不拋出異常的那種,不信?我們來試試

spring項目中切面及AOP的使用方法

@Around

這個是最為強大的一個注解,環繞通知,方法執行前和執行后都會執行加了這個注解的方法

@Around(value = 'execution (* own.study.web.OneController.*(..))') public Object doAround (ProceedingJoinPoint point) throws Throwable {Gson gson = new Gson();System.out.println('進入AOP --->' + System.currentTimeMillis());System.out.println('方法名 = ' + point.getSignature().toShortString()); Object result = point.proceed(); System.out.println('響應參數為 = ' + gson.toJson(result));System.out.println('AOP完事了 --->' + System.currentTimeMillis());return result; }

@RestControllerpublic class OneController { @GetMapping('/doCheck') public Object doCheck (int age) throws InterruptedException {System.out.println('這個是controller的方法 --->' + System.currentTimeMillis());Thread.sleep(2000l);System.out.println('doCheck');return new MyRsp('1', 'success'); } }

spring項目中切面及AOP的使用方法

但是,注意!這個環繞通知不是萬能的,不是一定好,大家按需要使用,比如一個場景,當你的方法拋出了異常,這個環繞通知就不會再繼續執行

我們來實驗一下

改寫controller的方法

@RestControllerpublic class OneController { @GetMapping('/doCheck') public Object doCheck (int age) throws InterruptedException {System.out.println('這個是controller的方法 --->' + System.currentTimeMillis());Thread.sleep(2000l);System.out.println('doCheck');throw new MyException('1', 'success'); // return new MyRsp('1', 'success'); } }

spring項目中切面及AOP的使用方法

看,AOP后續的沒有被執行

以上就是spring的切面,AOP的使用的詳細內容,更多關于spring的切面,AOP的使用的資料請關注好吧啦網其它相關文章!

標簽: Spring
相關文章:
国产综合久久一区二区三区