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接口。