项目实训8

项目实训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;
}

由于在本项目中,自定义注解的使用都是放在了拦截器、监听器进行判断的,所以没有显式定义具体的切面类。

具体使用请关注博客6博客7

以上,便完成了自定义的注解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值