springboot~aspect通过@annotation进行拦截

springboot~aspect通过@annotation进行拦截,第1张

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

愿与诸君共进步,大量的面试题及答案还有资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化、分布式架构等这些成为架构师必备的知识体系,可以微信搜索539413949获取,最后祝大家都能拿到自己心仪的offer

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/742332.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存