Springboot中使用自定義註解設定請求攔截器
Springboot中想要使用自定義註解需先新增基礎依賴
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.5.6.RELEASE</version>
- <relativePath/>
- </parent>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.8</java.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-aop</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
下圖是整個自定義註解的結構,其作用域於介面、類、列舉、註解
先講講自定義註解的組成元素類別
元註解是指註解的註解。包括 @Retention @Target @Document @Inherited四種。
@Retention的作用是定義註解的保留策略
@Retention(RetentionPolicy.SOURCE) //註解只在原始碼中產生作用 @Retention(RetentionPolicy.CLASS) // 預設的保留策略,註解會在class位元組碼檔案中存在,但執行時無法獲得, @Retention(RetentionPolicy.RUNTIME) // 註解會在class位元組碼檔案中存在,在執行時可以通過反射獲取到
通常使用的是@Retention(RetentionPolicy.RUNTIME) ,因為Springboot是依賴jar包執行的
@Target的作用是標誌這個註解用在某個目標上
@Target(ElementType.TYPE) //介面、類、列舉、註解 @Target(ElementType.FIELD) //欄位、列舉的常量 @Target(ElementType.METHOD) //方法 @Target(ElementType.PARAMETER) //方法引數 @Target(ElementType.CONSTRUCTOR) //建構函式 @Target(ElementType.LOCAL_VARIABLE)//區域性變數 @Target(ElementType.ANNOTATION_TYPE)//註解 @Target(ElementType.PACKAGE) ///包
註解就定義好了,接下來使用Springboot攔截器,建立類繼承HandlerInterceptor,並實現preHandle、postHandle、afterCompletion方法,
在preHandle中寫入攔截器的具體邏輯
如果請求沒有對映到方法,就直接通過攔截器,如果映射了就獲取到當前請求對應Controller的方法
判斷當前Controller介面是否需要驗證
如果Controller上有@TransmissionRequired註解,就開始驗證了,根據你的程式碼要求來判斷該條請求是否符合要求,從而判斷是否讓該請求進入Controller介面。