這篇文章主要介紹了springboot aspect通過@annotation進行攔截的案例分析,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
annotation就是注解的意思,在我們使用的攔截器時,可以通過業務層添加的某個注解,對業務方法進行攔截,之前我們在進行統一方法攔截時使用的是execution
,而注解的攔截我們使用@annotation
即可,我們可以做個例子,比如搞個防止重復提交的注解,然后在攔截器里去寫防止重復提交的邏輯就好了。
攔截器數據源
/** * 防止重復提交 * * @author BD-PC220 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface RepeatSubmit { /** * 間隔多長時間提交,默認1秒 * * @return */ long time() default 1; /** * 作為驗證重復提交的key, * * @return */ String key(); }
業務實現的攔截器代碼
/** * URL重復提交攔截器. */ @Slf4j @Component @Aspect public class RepeatSubmitAspect { @Autowired StringRedisTemplate redisTemplate; @Around("@annotation(repeatSubmit)") public Object around(ProceedingJoinPoint proceedingJoinPoint, RepeatSubmit repeatSubmit) throws Throwable { log.info("repeatSubmit={}", repeatSubmit.toString()); } }
在單元測試里去建立業務方法,然后建立單元測試的方法等
@Component public class RepeatSubmitController { @RepeatSubmit(key = "get") public String get() { return "success"; } }
測試代碼
@RunWith(SpringRunner.class) @SpringBootTest() @Slf4j public class RepeatSubmitTest { @Autowired RepeatSubmitController repeatSubmitController; @Test public void test() { log.info(repeatSubmitController.get()); } }
感謝你能夠認真閱讀完這篇文章,希望小編分享springboot aspect通過@annotation進行攔截的案例分析內容對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,遇到問題就找億速云,詳細的解決方法等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。