Spring Boot自定义配置的提示

使用Spring Boot的时候,填写配置信息(application.properties或application.yml)时,会出现提示。这种方式IDE也可以检查配置是否正确,对用户非常友好。本文介绍如何实现自定义配置的提示

添加自定义配置类


使用注解@ConfigurationProperties

@Component
@ConfigurationProperties(prefix = "blog")
public class BlogProperty {
    /**
     * blog's title
     */
    private String title;
    private String author;
    private boolean gender;
    private String national;
}

添加注解处理器

为配置类BlogProperty添加注解@ConfigurationProperties后,IDEA会出现红色提示Spring Boot Configuration Annotation Processor not found in classpath,这是因为还需要为注解配置处理器


  org.springframework.boot
  spring-boot-configuration-processor
  true

编译生成提示文件

  • 上一步添加注解处理器后,还是会出现绿色提示
    Re-run Spring Boot Configuration Annotation Processor to update generated metadata。该提示只是告诉我们去重新编译Spring Boot这样就可以更新生成的metadata文件,直接隐藏即可

  • 生成的文件如下classes/META-INF/spring-configuration-metadata.json

{
  "groups": [
    {
      "name": "blog",
      "type": "com.tenmao.property.BlogProperty",
      "sourceType": "com.tenmao.property.BlogProperty"
    }
  ],
  "properties": [
    {
      "name": "blog.author",
      "type": "java.lang.String",
      "sourceType": "com.tenmao.property.BlogProperty"
    },
    {
      "name": "blog.gender",
      "type": "java.lang.Boolean",
      "sourceType": "com.tenmao.property.BlogProperty",
      "defaultValue": false
    },
    {
      "name": "blog.national",
      "type": "java.lang.String",
      "sourceType": "com.tenmao.property.BlogProperty"
    },
    {
      "name": "blog.title",
      "type": "java.lang.String",
      "description": "blog's title",
      "sourceType": "com.tenmao.property.BlogProperty"
    }
  ],
  "hints": []
}
  • 很容易明白name, type, sourceType是如何从配置类生成的
  • 其中配置类中的注解会变成json中的description

使用

配置提示

手动修改

在自动生成的结果中再进行手动修改,比如为blog.national提供枚举值

"hints": [
  {
    "name": "blog.national",
    "values": [
      {
        "value": "China",
        "description": "People's Republic of China"
      },
      {
        "value": "Japan",
        "description": "Japan in Asia"
      }
    ]
  }
]
枚举值

误解

  • 很多地方都说需要在Spring Boot启动类上配置@EnableConfigurationProperties:实际上并不需要

参考

  • https://docs.spring.io/spring-boot/docs/current/reference/html/configuration-metadata.html
  • Re-run Spring Boot Configuration Annotation Processor to update generated metadata

你可能感兴趣的:(Spring Boot自定义配置的提示)