springboot實(shí)現(xiàn)對注解的切面案例
對注解實(shí)現(xiàn)切面案例:
(1)定義一個(gè)注解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { ? ? String getValues() default "test annotation"; }
@Target(ElementType.METHOD)
表示該注解作用在方法上(type表示類上,field表示成員變量上)
@Retention(RetentionPolicy.RUNTIME)
表示該注解的作用范圍,由于需要在運(yùn)行時(shí)能夠識別到該注解,所以是RUNTIME(SOURCE表示源碼層面上,即編譯成.class時(shí)看不見該注解,而CLASS可以,但是在運(yùn)行時(shí)看不到)
(2)編寫對注解的切面
(只是記錄的執(zhí)行時(shí)間和打印方法,可以實(shí)現(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í)行時(shí)間:{}", time); ? ? ? ? log.info("執(zhí)行類和方法:{} {}", className, methodName); ? ? ? ? return res; ? ? } }
(3)測試
@GetMapping("/go") @MyAnnotation(getValues = "success") public String test1() { ? ? return "hello world"; }
執(zhí)行結(jié)果:
注解上的值:success
執(zhí)行時(shí)間:8
執(zhí)行類和方法:com.***.TestController test1
到此這篇關(guān)于springboot實(shí)現(xiàn)對注解的切面案例的文章就介紹到這了,更多相關(guān)springboot實(shí)現(xiàn)對注解的切面內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Struts2實(shí)現(xiàn)文件上傳功能實(shí)例解析
這篇文章主要介紹了Struts2實(shí)現(xiàn)文件上傳功能實(shí)例解析,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-01-01Java使用Spring發(fā)送郵件的實(shí)現(xiàn)代碼
本篇文章主要介紹了使用Spring發(fā)送郵件的實(shí)現(xiàn)代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-03-03SpringBoot使用Spring Security實(shí)現(xiàn)登錄注銷功能
這篇文章主要介紹了SpringBoot使用Spring Security實(shí)現(xiàn)登錄注銷功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2020-09-09解決Spring?Boot應(yīng)用打包后文件訪問問題
在Spring Boot項(xiàng)目的開發(fā)過程中,一個(gè)常見的挑戰(zhàn)是如何有效地訪問和操作資源文件,本文就來介紹一下解決Spring?Boot應(yīng)用打包后文件訪問問題,感興趣的可以了解一下2024-01-01