Springboot - 配置元数据

64 阅读2分钟

前言

Spring框架里的元数据配置功能,可以在IDE内进行配置属性的便捷提示和自动完成,方便程序员快速检索可选属性和相应的取值范围,避免人为的拼写错误,降低程序bug概率。

官方帮助文档地址:www.docs4dev.com/docs/zh/spr…

常见场景

  • 可以看出password和address这两个配置项都是黄色标志【warn】,当然,也不会有任何代码提示
    image.png
  • 编译之后的代码,classes文件夹下面,没有META-INF目录
    image.png

Maven配置

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
  • 重新编译之后,生成META-INF目录
    image.png
    包含文件【spring-configuration-metadata.json】
  • 配置文件里的黄色告警也消失
    image.png
  • 可选属性自动提示和默认值设置
    image.png

关键参数介绍

主要就是文件【spring-configuration-metadata.json】的生成,里面包含了一系列分组和属性的说明。

groups

spring中每个设定了注解【@ConfigurationProperties】的Java类都会自动生成一个组,比如:@ConfigurationProperties(prefix="spring.redisson"),会生成group:

    {
      "name": "spring.redisson",
      "type": "com.test.xxx.config.RedissonClusterConfig",
      "sourceType": "com.test.xxx.config.RedissonClusterConfig"
    }

properties

具体某个属性的介绍,例如在RedissonClusterConfig中的thread字段,会生成对应的json属性说明;


    /**
     * 执行Topic监听和removeService的线程
     */
    private int thread = 32;

    {
      "name": "spring.redisson.thread",
      "type": "java.lang.Integer",
      "description": "执行Topic监听和removeService的线程",
      "sourceType": "com.test.xxx.config.RedissonClusterConfig",
      "defaultValue": 32
    },

hints

属性值的可选范围,比如我们设定redisson里的database值只能选0和1

  "hints": [
      {
      "name": "spring.redisson.database",
      "values": [
          {
            "value": "0"
          },
          {
            "value": "1"
          }
        ]
    }
  ]

那么在自动完成的提示里,会出现【0】和【1】的选项
image.png

  • hints.providers
    当然,此处也只允许输入0和1,输入其他值时,编辑器会给出报错告警提示。为什么呢,这是因为我们在【spring-configuration-metadata.json】配置里没有允许database属性自定义取值;
    image.png
    如何避免这种问题呢?需要添加如下配置:
  "hints": [
      {
      "name": "spring.redisson.database",
      "values": [
          {
            "value": "0"
          },
          {
            "value": "1"
          }
        ],
        "providers": [
{
"name": "any"
}
]
    }
  ]

立竿见影,不报错了
image.png