溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

springboot aspect通過(guò)@annotation進(jìn)行攔截的案例分析

發(fā)布時(shí)間:2020-08-20 13:54:35 來(lái)源:億速云 閱讀:197 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹了springboot aspect通過(guò)@annotation進(jìn)行攔截的案例分析,具有一定借鑒價(jià)值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。

annotation就是注解的意思,在我們使用的攔截器時(shí),可以通過(guò)業(yè)務(wù)層添加的某個(gè)注解,對(duì)業(yè)務(wù)方法進(jìn)行攔截,之前我們?cè)谶M(jìn)行統(tǒng)一方法攔截時(shí)使用的是execution,而注解的攔截我們使用@annotation即可,我們可以做個(gè)例子,比如搞個(gè)防止重復(fù)提交的注解,然后在攔截器里去寫防止重復(fù)提交的邏輯就好了。

攔截器數(shù)據(jù)源

/**
 * 防止重復(fù)提交
 *
 * @author BD-PC220
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface RepeatSubmit {
  /**
   * 間隔多長(zhǎng)時(shí)間提交,默認(rèn)1秒
   *
   * @return
   */
  long time() default 1;

  /**
   * 作為驗(yàn)證重復(fù)提交的key,
   *
   * @return
   */
  String key();
}

業(yè)務(wù)實(shí)現(xiàn)的攔截器代碼

/**
 * URL重復(fù)提交攔截器.
 */
@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());
  }
}

在單元測(cè)試?yán)锶ソI(yè)務(wù)方法,然后建立單元測(cè)試的方法等

@Component
public class RepeatSubmitController {
  @RepeatSubmit(key = "get")
  public String get() {
    return "success";
  }
}

測(cè)試代碼

@RunWith(SpringRunner.class)
@SpringBootTest()
@Slf4j
public class RepeatSubmitTest {
  @Autowired
  RepeatSubmitController repeatSubmitController;

  @Test
  public void test() {
    log.info(repeatSubmitController.get());
  }
}

springboot aspect通過(guò)@annotation進(jìn)行攔截的案例分析

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享springboot aspect通過(guò)@annotation進(jìn)行攔截的案例分析內(nèi)容對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,遇到問(wèn)題就找億速云,詳細(xì)的解決方法等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI