Spring Boot 如何获取@ApiModelProperty(value = “序列号“, name = “uuid“)中的value值name值?
  HptQjPcX5vAL 2023年11月21日 45 0

前言

在 Spring Boot 项目中,经常需要使用 Swagger 来生成文档和测试接口。在 Swagger 中,我们可以使用 @ApiModelProperty 注解来对字段进行描述,例如添加字段名(name)和字段注释(value)。但是,在实际开发中,有时候我们需要获取这些注解中的值,以便于后续的处理。本文将介绍如何获取 @ApiModelProperty 注解中的 value 值和 name 值。

摘要

本文将结合源代码解析和实例应用场景,介绍如何在 Spring Boot 项目中获取 @ApiModelProperty 注解中的 value 值和 name 值。

简介

Swagger 是一个开源的接口文档生成工具,可以直接生成 API 文档和测试接口,并且可以方便地进行测试和调试。在 Spring Boot 项目中,我们通过引入 springfox-swagger2 和 springfox-swagger-ui 两个依赖来集成 Swagger。然后,我们可以使用 @ApiModelProperty 注解来对字段进行描述,例如添加字段名(name)和字段注释(value)。@ApiModelProperty 注解的定义如下:

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface ApiModelProperty {
    String value() default "";
    String name() default "";
    boolean required() default false;
    String allowableValues() default "";
    boolean hidden() default false;
    boolean readOnly() default false;
    boolean allowEmptyValue() default true;
    int position() default 0;
    String example() default "";
    Class<?>[] reference() default {};
    String access() default "";
    Class<?> type() default Void.class;
    Union[] unions() default {};

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Union {
        Class<?>[] implementation() default {};

        boolean anyOf() default false;
    }
}

其中,value 属性表示字段注释,name 属性表示字段名。

源代码解析

我们可以通过反射来获取类中的字段上的 @ApiModelProperty 注解,然后获取其 value 和 name 属性的值。

以下是获取 value 和 name 属性值的示例代码:

import io.swagger.annotations.ApiModelProperty;
import java.lang.reflect.Field;

public class GetAnnotationValueExample {
    @ApiModelProperty(value = "序列号", name = "uuid")
    private String serialNumber;

    public static void main(String[] args) throws NoSuchFieldException {
        Field field = GetAnnotationValueExample.class.getDeclaredField("serialNumber");
        ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
        String value = annotation.value();// 序列号
        String name = annotation.name();// uuid
        System.out.println("value: " + value);
        System.out.println("name: " + name);
    }
}

上面的代码中,我们通过反射获取 GetAnnotationValueExample 类中的 serialNumber 字段上的 @ApiModelProperty 注解,然后获取其 value 和 name 属性的值。

应用场景案例

在实际开发中,我们有时候需要根据字段名来获取对应的 @ApiModelProperty 注解中的 value 值和 name 值。例如,我们在处理 Excel 文件时,需要根据表头名称获取对应字段的值。具体实现可以参考以下示例代码:

import io.swagger.annotations.ApiModelProperty;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class GetAnnotationValueByNameExample {
    @ApiModelProperty(value = "序列号", name = "uuid")
    private String serialNumber;

    public static void main(String[] args) {
        GetAnnotationValueByNameExample example = new GetAnnotationValueByNameExample();
        Map<String, String> map = example.getFieldNameAndValue();
        String value = map.get("uuid");// 序列号
        System.out.println("value: " + value);
    }

    public Map<String, String> getFieldNameAndValue() {
        Map<String, String> map = new HashMap<>();
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(ApiModelProperty.class)) {
                ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
                String fieldName = annotation.name();
                String fieldValue = "";
                field.setAccessible(true);
                try {
                    fieldValue = (String) field.get(this);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                map.put(fieldName, fieldValue);
            }
        }
        return map;
    }
}

上面的代码中,我们首先获取到 GetAnnotationValueByNameExample 类中的所有字段,然后遍历字段,判断字段上是否有 @ApiModelProperty 注解。如果存在,就获取其 name 和 value 属性的值,并将其保存到一个 Map 中。最终,我们可以根据 name 来获取对应的 value 值。

优缺点分析

通过反射获取 @ApiModelProperty 注解中的 value 和 name 属性的值,可以方便地对被描述的字段进行处理。但是,使用反射会带来一定的性能损失,应该谨慎使用。同时,如果在项目中对字段名进行了重命名,那么获取注解中的 name 属性值可能会失败。

类代码方法介绍

getAnnotationValue

public static String getAnnotationValue(Field field, Class annotationClass, String attributeName) {
    if (field.isAnnotationPresent(annotationClass)) {
        Annotation annotation = field.getAnnotation(annotationClass);
        try {
            Method method = annotationClass.getMethod(attributeName);
            return (String) method.invoke(annotation);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

这个方法可以根据属性名来获取对应注解中的属性值。

getFieldNameAndValue

public Map<String, String> getFieldNameAndValue(Class clazz, Object object) {
    Map<String, String> map = new HashMap<>();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        String fieldName = field.getName();
        String fieldValue = "";
        field.setAccessible(true);
        try {
            fieldValue = (String) field.get(object);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        map.put(fieldName, fieldValue);
    }
    return map;
}

这个方法可以获取一个对象中所有字段的名称和值,并将其保存到一个 Map 中。

测试用例

以下是一个测试用例,用来测试 getAnnotationValue 方法和 getFieldNameAndValue 方法的正确性。

import io.swagger.annotations.ApiModelProperty;
import java.lang.reflect.Field;
import java.util.Map;

public class AnnotationTest {
    @ApiModelProperty(value = "序列号", name = "uuid")
    private String serialNumber;

    public static void main(String[] args) throws NoSuchFieldException {
        AnnotationTest test = new AnnotationTest();
        String value = test.getAnnotationValue("serialNumber", ApiModelProperty.class, "value");// 序列号
        System.out.println("value: " + value);

        Map<String, String> map = test.getFieldNameAndValue(test.getClass(), test);
        String fieldValue = map.get("serialNumber");// abc
        System.out.println("fieldValue: " + fieldValue);
    }

    public String getAnnotationValue(String fieldName, Class annotationClass, String attributeName) throws NoSuchFieldException {
        Field field = this.getClass().getDeclaredField(fieldName);
        return AnnotationUtils.getAnnotationValue(field, annotationClass, attributeName);
    }
}

全文小结

本文介绍了如何在 Spring Boot 项目中获取 @ApiModelProperty 注解中的 value 值和 name 值。我们可以通过反射获取类中的字段上的 @ApiModelProperty 注解,然后获取其 value 和 name 属性的值。本文还给出了实际应用场景案例,以及方法的优缺点分析和代码方法介绍。

总结

在开发中,有时候我们需要获取注解中的属性值,以便于后续的处理。通过反射,我们可以轻松地获取 @ApiModelProperty 注解中的 value 值和 name 值,方便进行处理。但是,反射会带来一定的性能损失,应该谨慎使用。

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月21日 0

暂无评论

推荐阅读
  2Vtxr3XfwhHq   2024年05月17日   55   0   0 Java
  Tnh5bgG19sRf   2024年05月20日   110   0   0 Java
  8s1LUHPryisj   2024年05月17日   46   0   0 Java
  aRSRdgycpgWt   2024年05月17日   47   0   0 Java
HptQjPcX5vAL