1.自定义注解

注解定义

  1. 由于spring中使用了大量自定义注解,所以先对介绍一下自定义注解
  2. 首先新建注解类
//生命周期存在运行时
//@Retention(RetentionPolicy.RUNTIME)
// 生命周期存在类中
@Retention(RetentionPolicy.RUNTIME) // 生命周期
//@Target(ElementType.CONSTRUCTOR)
public @interface Hw {
    public String value() default "";

    public int age() default 2;
}

  1. 注解生命周期 @Retention
    1. SOURCE:注解只保留在源代码中,编译时丢弃
    2. CLASS:注解保留class文件中,在JVM运行时被忽略
    3. RUNTIME:注解记录在class文件中并被JVM保留,可以使用反射读取
  2. 指定注解作用位置:@Target,以下列出常用位置
    1. TYPE 作用到类
    2. FIELD 作用到类字段
    3. METHOD 作用到方法

注解使用

  1. 定义实体类
@Hw(value = "ww",age = 20)
@Slf4j
public class Member {


    @Hw(value = "name",age = 100)
    public String name;

    @Hw
    public Member() {
    }

    @Hw(value = "method",age = 200)
    public void memberMethod(){
        log.debug("xxx");
    }
}

  1. 获取实体类中注解信息
public static void main(String[] args) {
        Class<Member> clazz = Member.class;
//        判断类中是否有指定注解
        if (clazz.isAnnotationPresent(Hw.class)) {
            Hw annotation = clazz.getAnnotation(Hw.class);
            String value = annotation.value();
            int age = annotation.age();
            log.debug("class annotation value: {},age: {}",value,age);
        }


//        拿到方法中的注解信息
        try {
            Method memberMethod = clazz.getMethod("memberMethod");
            Hw annotation = memberMethod.getAnnotation(Hw.class);
            log.debug("method annotation value: {}, age:{}",annotation.value(),annotation.age());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

//      获取类字段注解
        try {
            Field name = clazz.getField("name");
            Hw annotation = name.getAnnotation(Hw.class);
            log.debug("Field annotation value: {}, age: {}",annotation.value(),annotation.age());
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }
posted @ 2023-04-18 15:55  渔阳nice  阅读(14)  评论(0)    收藏  举报