springboot實現(xiàn)對注解的切面案例
對注解實現(xiàn)切面案例:
(1)定義一個注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
? ? String getValues() default "test annotation";
}@Target(ElementType.METHOD)
表示該注解作用在方法上(type表示類上,field表示成員變量上)
@Retention(RetentionPolicy.RUNTIME)
表示該注解的作用范圍,由于需要在運行時能夠識別到該注解,所以是RUNTIME(SOURCE表示源碼層面上,即編譯成.class時看不見該注解,而CLASS可以,但是在運行時看不到)
(2)編寫對注解的切面
(只是記錄的執(zhí)行時間和打印方法,可以實現(xiàn)其他邏輯)
@Aspect
@Component
@Slf4j
public class MyAspect {
? ? // value也可以寫成value = "(execution(* com.sj..*(..))) && @annotation(zkDistributeLock)"
? ? @Around(value = "@annotation(myAnnotation)", argNames = "proceedingJoinPoint, myAnnotation")
? ? public Object processTest(ProceedingJoinPoint proceedingJoinPoint, MyAnnotation myAnnotation) throws Throwable {
? ? ? ? long beginTime = System.currentTimeMillis();
? ? ? ? // 獲取方法參數(shù)
? ? ? ? Object[] args = proceedingJoinPoint.getArgs();
? ? ? ? // 執(zhí)行方法
? ? ? ? Object res = proceedingJoinPoint.proceed(args);
? ? ? ? long time = System.currentTimeMillis() - beginTime;
? ? ? ? MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
? ? ? ? String className = proceedingJoinPoint.getTarget().getClass().getName();
? ? ? ? String methodName = signature.getName();
? ? ? ? log.info("注解上的值:{}", myAnnotation.getValues());
? ? ? ? log.info("執(zhí)行時間:{}", time);
? ? ? ? log.info("執(zhí)行類和方法:{} {}", className, methodName);
? ? ? ? return res;
? ? }
}(3)測試
@GetMapping("/go")
@MyAnnotation(getValues = "success")
public String test1() {
? ? return "hello world";
}執(zhí)行結(jié)果:
注解上的值:success
執(zhí)行時間:8
執(zhí)行類和方法:com.***.TestController test1
到此這篇關(guān)于springboot實現(xiàn)對注解的切面案例的文章就介紹到這了,更多相關(guān)springboot實現(xiàn)對注解的切面內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java面向?qū)ο蠡A(chǔ)知識之委托和lambda
這篇文章主要介紹了Java面向?qū)ο蟮闹泻?lambda,文中有非常詳細的代碼示例,對正在學(xué)習(xí)java基礎(chǔ)的小伙伴們有很好的幫助,需要的朋友可以參考下2021-11-11
IDEA在plugins里搜不到mybatisx插件的解決方法
本文主要介紹了IDEA在plugins里搜不到mybatisx插件的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
Java多線程實現(xiàn)模擬12306火車站售票系統(tǒng)
12360火車票售票系統(tǒng)基本上大家都用過,那你知道是怎么實現(xiàn)的嗎,今天我們就模擬12306火車站售票系統(tǒng)來實現(xiàn),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
Spring Boot創(chuàng)建非可執(zhí)行jar包的實例教程
這篇文章主要介紹了Spring Boot創(chuàng)建非可執(zhí)行jar包的實例教程,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
ByteArrayOutputStream簡介和使用_動力節(jié)點Java學(xué)院整理
ByteArrayOutputStream 是字節(jié)數(shù)組輸出流。它繼承于OutputStream。這篇文章主要介紹了ByteArrayOutputStream簡介和使用,需要的朋友可以參考下2017-05-05
JSP request.setAttribute()詳解及實例
這篇文章主要介紹了 javascript request.setAttribute()詳解及實例的相關(guān)資料,需要的朋友可以參考下2017-02-02
springmvc @RequestBody String類型參數(shù)的使用
這篇文章主要介紹了springmvc @RequestBody String類型參數(shù)的使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10

