Springboot中使用自定义注解设置请求拦截器

Springboot中想要使用自定义注解需先添加基础依赖

  1. <parent>  
  2.         <groupId>org.springframework.boot</groupId>  
  3.         <artifactId>spring-boot-starter-parent</artifactId>  
  4.         <version>1.5.6.RELEASE</version>  
  5.         <relativePath/> 
  6.     </parent>  
  7.  
  8.     <properties>  
  9.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  10.         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
  11.         <java.version>1.8</java.version>  
  12.     </properties>  
  13.   
  14.     <dependencies>  
  15.         <dependency>  
  16.             <groupId>org.springframework.boot</groupId>  
  17.             <artifactId>spring-boot-starter-aop</artifactId>  
  18.         </dependency>  
  19.         <dependency>  
  20.             <groupId>org.springframework.boot</groupId>  
  21.             <artifactId>spring-boot-starter-web</artifactId>  
  22.         </dependency>  
  23.         <dependency>  
  24.             <groupId>org.springframework.boot</groupId>  
  25.             <artifactId>spring-boot-starter-test</artifactId>  
  26.             <scope>test</scope>  
  27.         </dependency>  
  28.     </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接口。

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值