当前位置: 移动技术网 > IT编程>开发语言>Java > springboot aspect通过@annotation进行拦截的实例代码详解

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

2020年08月20日  | 移动技术网IT编程  | 我要评论
annotation就是注解的意思,在我们使用的拦截器时,可以通过业务层添加的某个注解,对业务方法进行拦截,之前我们在进行统一方法拦截时使用的是execution,而注解的拦截我们使用@annotat

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拦截内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网