springboot aspect通过@annotation进行拦截的实例代码详解

这篇文章主要介绍了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进行拦截的文章就介绍到这了,更多相关springboot aspect通过@annotation拦截内容请搜索html中文网以前的文章或继续浏览下面的相关文章希望大家以后多多支持html中文网!

以上就是springboot aspect通过@annotation进行拦截的实例代码详解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java