springboot實現對注解的切面案例
對注解實現切面案例:
(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í)行時間和打印方法,可以實現其他邏輯)
@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();
? ? ? ? // 獲取方法參數
? ? ? ? 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í)行結果:
注解上的值:success
執(zhí)行時間:8
執(zhí)行類和方法:com.***.TestController test1
到此這篇關于springboot實現對注解的切面案例的文章就介紹到這了,更多相關springboot實現對注解的切面內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
IDEA在plugins里搜不到mybatisx插件的解決方法
本文主要介紹了IDEA在plugins里搜不到mybatisx插件的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-06-06
Spring Boot創(chuàng)建非可執(zhí)行jar包的實例教程
這篇文章主要介紹了Spring Boot創(chuàng)建非可執(zhí)行jar包的實例教程,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
ByteArrayOutputStream簡介和使用_動力節(jié)點Java學院整理
ByteArrayOutputStream 是字節(jié)數組輸出流。它繼承于OutputStream。這篇文章主要介紹了ByteArrayOutputStream簡介和使用,需要的朋友可以參考下2017-05-05
JSP request.setAttribute()詳解及實例
這篇文章主要介紹了 javascript request.setAttribute()詳解及實例的相關資料,需要的朋友可以參考下2017-02-02
springmvc @RequestBody String類型參數的使用
這篇文章主要介紹了springmvc @RequestBody String類型參數的使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10

