【Spring注解】自定义注解编程实战

本文详细解析编译时注解与运行时注解的区别及应用,通过实例展示了如何使用注解处理器在编译阶段生成代码,以及如何在运行时通过反射读取注解信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本篇文章将通过Demo来说说编译时注解和运行时注解。

一、 运行时注解

运行时注解是通过反射在程序运行时获取注解信息,然后利用信息进行其他处理。下面是运行时注解的一个简单Damo,包含Company、EmployeeName、EmployeeSex注解定义以及EmployeeInfoUtil注解处理器,客户端包含EmployeeInfo类(成员变量使用注解)和一个main方法。
Compay代码:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Company {
    public int id() default -1;
    public String name() default "";
    public String address() default "";
}

EmployeeName代码:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EmployeeName {
    String value () default "";
}

EmployeeSex代码:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EmployeeSex {
    enum Sex{Man,Woman}//定义性别枚举
    Sex employeeSex()  default Sex.Man;
}

注解处理器

public class EmployeeInfoUtil {
    public static Map getEmployeeInfo(Class<?> clazz){
        HashMap<String ,String> info = new HashMap<>();
        Field[] fields = clazz.getDeclaredFields();//获取类成员变量
        for (Field field: fields) {//遍历
            if (field.isAnnotationPresent(EmployeeName.class)){//判断是不是EmployeeName类型注解
                EmployeeName employeeName = field.getAnnotation(EmployeeName.class);
                info.put("employeeName",employeeName.value());//获取注解的值
            }
            if (field.isAnnotationPresent(EmployeeSex.class)) {
                EmployeeSex employeeSex = field.getAnnotation(EmployeeSex.class);
                info.put("employeeSex",employeeSex.employeeSex().toString());
            }
            if (field.isAnnotationPresent(Company.class)) {
                Company company = field.getAnnotation(Company.class);
                info.put("company",company.id()+":"+company.name()+":"+company.address());
            }
        }
        return info;
    }

EmployeeInfo代码:

public class EmployeeInfo {
    @EmployeeName("zfq")
    private String employeeName;
    @EmployeeSex(employeeSex = EmployeeSex.Sex.Woman)
    private String employeeSex;
    @Company(id = 1,name = "文华集团",address = "河北衡水")
    private String company;
}

客户端代码:

@RequestMapping("runtimeAnnotation")
    public Map getAnnotationInfos() {
        return EmployeeInfoUtil.getEmployeeInfo(EmployeeInfo.class);
    }

运行结果:http://127.0.0.1:8080/test/runtimeAnnotation

{

    "employeeName": "zfq",
    "employeeSex": "Woman",
    "company": "1:文华集团:河北衡水"

}

二、编译时注解

编译时注解是在程序编译的时候动态的生成一些类或者文件,所以编译时注解不会影响程序运行时的性能,而运行时注解则依赖于反射,反射肯定会影响程序运行时的性能,所以一些知名的三方库一般都是使用编译时时注解,比如大名鼎鼎的ButterKnife、Dagger、Afinal等。

下面编译时注解是编译时打印使用指定注解的方法的方法信息,注解的定义和运行时注解一样,主要是注解处理器对注解的处理不同 。
@InjectPrint注解代码

@Target({ElementType.FIELD, ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.CLASS)
public @interface InjectPrint {
   String value();
}

InjectPrintProcessor处理器代码:

@SupportedAnnotationTypes("com.ratel.InjectPrint")//参数是指定注解类型的全路径
public class InjectPrintProcessor extends AbstractProcessor {

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        //获取InjectPrint类型注解,然后遍历
        for(Element element : roundEnvironment.getElementsAnnotatedWith(InjectPrint.class)){
            //元素类型是一个方法
            if(element.getKind() == ElementKind.METHOD){
                //强转成方法对应的element,同
                // 理,如果你的注解是一个类,那你可以强转成TypeElement
                ExecutableElement executableElement = (ExecutableElement)element;
                //打印方法名
                System.out.println(executableElement.getSimpleName());
                //打印方法的返回类型
                System.out.println(executableElement.getReturnType().toString());
                //获取方法所有的参数
                List<? extends VariableElement> params = executableElement.getParameters();
                for(VariableElement variableElement : params){//遍历并打印参数名
                    System.out.println(variableElement.getSimpleName());
                }
                //打印注解的值
                System.out.println("AnnotationValue:"+executableElement.getAnnotation(InjectPrint.class).value());
            }
        }
        return false;
    }

    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latestSupported();
    }
}

为了我们的AbstractProcessor内被使用,需要在META-INF中显示标识,在resources资源文件夹下新建 META-INF/services/javax.annotation.processing.Processor,其内容:

 com.example.InjectPrintProcessor //注解处理器的全路径

具体的目录结构如下图所示:

到此我们就可以build整个工程, 生成jar包了,如下图

我们可以把myanno.jar拷贝出来,添加到主工程的libs文件夹里,别忘Add As Library
然后,我们就可以在我们的主工程里使用@InjectPrint注解了

Build我们的项目,然后Gradle Console控制台就可以看到输出信息了

注意:如果你编译过一次下次可能在build的时候可能就看不到控制台输出,这时候你要选择Rebuild Project
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值