项目实训8
1. 背景
在开发SpringBoot程序的过程中,有可能与其他业务系统进行对接开发,有的时候为了开发的便捷性以及间接性,会需要开发一些自定义的注解,来实现一些业务。比如我们之前博客提到的实现mongodb数据库的自增id以及token的验证
下面就来说一下在SpringBoot里开发自定义注解。
2. 过程
首先添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
下面是定义注解的一些原注解:
@Target
:注解的作用目标。@Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了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)
——包
@Retention
:注解的保留位置
RetentionPolicy.SOURCE
:这种类型的Annotations
只在源代码级别保留,编译时就会被忽略,在class
字节码文件中不包含。
RetentionPolicy.CLASS
:这种类型的Annotations
编译时被保留,默认的保留策略,在class
文件中存在,但JVM
将会忽略,运行时无法获得。
RetentionPolicy.RUNTIME
:这种类型的Annotations
将被JVM
保留,所以他们能在运行时被JVM
或其他使用反射机制的代码所读取和使用。
@Document
:说明该注解将被包含在javadoc
中
@Inherited
:说明子类可以继承父类中的该注解
具体代码实现:
自增操作定义的注解:
package com.example.guke.annotation;
/**
* @program: GuKe
* @description: 自增字段注解
* @author: NiuYiq
* @date: 2022-04-05 09:54
**/
import java.lang.annotation.*;
/**
* 定义一个主键自增的标志注解
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface AutoInc
{
}
跨文档原子操作使用的注解
package com.example.guke.annotation;
import java.lang.annotation.*;
/**
* @program: GuKe
* @description: 跨文档递减字段-post的评论数量字段
* @author: NiuYiq
* @date: 2022-04-16 14:40
**/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface AutoDec
{
}
用户不需要验证token的注解
package com.example.guke.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken
{
boolean required() default true;
}
用户需要验证token的注解
package com.example.guke.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken
{
boolean required() default true;
}
由于在本项目中,自定义注解的使用都是放在了拦截器、监听器进行判断的,所以没有显式定义具体的切面类。
以上,便完成了自定义的注解。