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

网友投稿 289 2022-11-26


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

annotation就是注解的意思,在我们使用的拦截器时,可以通过业务层添加的某个注解,对业务方法进行拦截,之前我们在进行统一方法拦截时使用的是exeHBnBjPcution,而注解的拦截我们使用@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());

}

}

在单元测试里去建立业务方法,然后建立单元测试的方法等

@ComponentHBnBjP

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());

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java调用pyzbar解析base64二维码过程解析
下一篇:Java中final关键字的使用与注意总结
相关文章

 发表评论

暂时没有评论,来抢沙发吧~