SpringBoot 自定义注解(元解)

定义注解类

@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:注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃;
        RetentionPolicy.CLASS:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期;
        RetentionPolicy.RUNTIME:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在;

编码

@Target(value = ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
	String value();
}

然后写个实体类给加上去

@MyAnnotation("肥宅")
public class User {

}

然后调用实体类

public class Demo {
	public static void main(String[] args) {
		Class userClass = User.class;
		// 获取注解
		MyAnnotation annotation =(MyAnnotation) userClass.getAnnotation(MyAnnotation.class);
		// 获取注解的值
		String value = annotation.value();
		System.out.println(value);
	}
}

输出,得到的实体类,注解的值
在这里插入图片描述

再定义一个属性字段上的注解

    注意@Target注解里面的类型要写成FIELD

@Target(value = ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyFieldAnnotation {
	String cloumnName();
	String type();
	int length();
}

现在给实体类加上字段,获取字段上的注解值

@MyAnnotation("肥宅")
public class User {
	@MyFieldAnnotation(cloumnName = "db_name",type = "String",length = 10)
	String name;
	@MyFieldAnnotation(cloumnName = "db_age",type = "int",length = 10)
	int age;
}

比如获取某一个字段上的注解,如 name

public class Demo {
	public static void main(String[] args) throws NoSuchFieldException {
		Class userClass = User.class;
		// 获取类指定的注解
		Field name = userClass.getDeclaredField("name");
		MyFieldAnnotation annotation1 = name.getAnnotation(MyFieldAnnotation.class);
		// 注解里面的定义的属性:.cloumnName() .type() .length()
		System.out.println(annotation1.cloumnName());
		System.out.println(annotation1.type());
		System.out.println(annotation1.length());
	}
}

输出为
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值