SpringBoot基于自定義注解實現(xiàn)切面編程
1、相關依賴包
<!-- aop 依賴包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.6</version> </dependency>
2、定義切面類
package com.bz.aspect;import com.bz.service.SysLogOperationService;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;/** * 操作日志,切面處理類 */@Aspect@Componentpublic class LogOperationAspect { @Autowired(required = false) private SysLogOperationService sysLogOperationService; @Pointcut('@annotation(com.bz.aspect.BzLogOperation)') public void logPointCut() { System.out.println('lllll'); } /** * 前置通知:方法執(zhí)行前調用 */ @Before('logPointCut()') public void begin() { System.out.println('前置通知:方法執(zhí)行前調用'); } /** * 后置通知: 方法執(zhí)行后調用,若方法出現(xiàn)異常,不執(zhí)行 */ @AfterReturning('logPointCut()') public void afterReturning() { System.out.println('后置通知: 方法執(zhí)行后調用,若方法出現(xiàn)異常,不執(zhí)行'); } /** * 最終通知:無論無何都會調用,類似于:try/catch中的finally */ @After('logPointCut()') public void after() { System.out.println('最終通知:無論無何都會調用,類似于:try/catch中的finally'); } /** * 異常通知:方法拋出異常時執(zhí)行 */ @AfterThrowing('logPointCut()') public void afterThrowing() { System.out.println('異常通知:方法拋出異常時執(zhí)行'); } /** * 環(huán)繞通知 * 既可以在目標方法之前織入增強動作,也可以在執(zhí)行目標方法之后織入增強動作; * 可以決定目標方法在什么時候執(zhí)行,如何執(zhí)行,甚至可以完全阻止目標目標方法的執(zhí)行; * 可以改變執(zhí)行目標方法的參數(shù)值,也可以改變執(zhí)行目標方法之后的返回值; 當需要改變目標方法的返回值時,只能使用Around方法; */ @Around('logPointCut()') public void around(ProceedingJoinPoint point) throws Throwable { // 獲取切點方法的名稱 String methodName = point.getSignature().getName(); // 獲取方法傳入?yún)?shù) Object[] params = point.getArgs(); //轉成字符串 List<Object> objects = Arrays.asList(params); objects.forEach(obj -> System.out.println(JSON.toJSONString(obj))); System.out.println('環(huán)繞通知'); }}
3、自定義切面注解類
package com.bz.aspect;import java.lang.annotation.*;/** * @author: BuZheng * @date: 2020-05-18 下午 2:02 */@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface BzLogOperation { String value() default '';}
4、接口測試
@ApiOperation('切面測試') @GetMapping('/aop') @BzLogOperation('切面測試') public ResultBean userList(@RequestParam(value = 'keyWord') String keyWord) { log.info('### 切面測試 ###'); return new ResultBean(); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關文章:
1. vue-drag-chart 拖動/縮放圖表組件的實例代碼2. vue使用moment如何將時間戳轉為標準日期時間格式3. Android studio 解決logcat無過濾工具欄的操作4. 什么是Python變量作用域5. js select支持手動輸入功能實現(xiàn)代碼6. PHP正則表達式函數(shù)preg_replace用法實例分析7. Android Studio3.6.+ 插件搜索不到終極解決方案(圖文詳解)8. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼9. Android 實現(xiàn)徹底退出自己APP 并殺掉所有相關的進程10. 一個 2 年 Android 開發(fā)者的 18 條忠告
