一、背景

官方提供的spring boot starter的配置项,我们用IDE配置的时候一般都有自动提示的,如下图所示。
yml自定义配置自动提示 - 图1
而我们自己自定义的配置却没有,对开发非常不友好容易打错配置,那这个是怎样实现的呢?

二、提示原理

IDE是通过读取配置信息的元数据而实现自动提示的,而元数据在目录META-INF中的spring-configuration-metadata.json或者additional-spring-configuration-metadata.json

三、实现自动提示

以我这个自己开发的starter中的自定义配置文件为例,如果自己手动创建这些元数据的话工作量比较大,使用IDEA的话有自动生成功能

  1. @Data
  2. @EqualsAndHashCode(callSuper = true)
  3. @Configuration
  4. @ConfigurationProperties(prefix = "translation.baidu")
  5. @ConditionalOnProperty(prefix = "translation", value = "baidu.enabled", havingValue = "true")
  6. public class BaiduTranslationProperties extends BasicProperties {
  7. /**
  8. * app id
  9. */
  10. private String appId;
  11. /**
  12. * securityKey
  13. */
  14. private String securityKey;
  15. }

3.1. 引入依赖spring-boot-configuration-processor

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-configuration-processor</artifactId>
  4. <optional>true</optional>
  5. </dependency>

3.2. 编译项目

项目在重新编译后就会在META-INF自动生成spring-configuration-metadata.json文件。

  1. {
  2. "groups": [
  3. {
  4. "name": "translation.baidu",
  5. "type": "com.vevor.tools.translation.config.properties.BaiduTranslationProperties",
  6. "sourceType": "com.vevor.tools.translation.config.properties.BaiduTranslationProperties"
  7. },
  8. {
  9. "name": "translation.google",
  10. "type": "com.vevor.tools.translation.config.properties.GoogleTranslationProperties",
  11. "sourceType": "com.vevor.tools.translation.config.properties.GoogleTranslationProperties"
  12. }
  13. ],
  14. "properties": [
  15. {
  16. "name": "translation.baidu.app-id",
  17. "type": "java.lang.String",
  18. "description": "app id",
  19. "sourceType": "com.vevor.tools.translation.config.properties.BaiduTranslationProperties"
  20. },
  21. {
  22. "name": "translation.baidu.enabled",
  23. "type": "java.lang.Boolean",
  24. "description": "是否开启",
  25. "sourceType": "com.vevor.tools.translation.config.properties.BaiduTranslationProperties"
  26. },
  27. {
  28. "name": "translation.baidu.security-key",
  29. "type": "java.lang.String",
  30. "description": "securityKey",
  31. "sourceType": "com.vevor.tools.translation.config.properties.BaiduTranslationProperties"
  32. },
  33. {
  34. "name": "translation.baidu.url",
  35. "type": "java.lang.String",
  36. "description": "设置域名地址",
  37. "sourceType": "com.vevor.tools.translation.config.properties.BaiduTranslationProperties"
  38. },
  39. {
  40. "name": "translation.google.enabled",
  41. "type": "java.lang.Boolean",
  42. "description": "是否开启",
  43. "sourceType": "com.vevor.tools.translation.config.properties.GoogleTranslationProperties"
  44. },
  45. {
  46. "name": "translation.google.url",
  47. "type": "java.lang.String",
  48. "description": "设置域名地址",
  49. "sourceType": "com.vevor.tools.translation.config.properties.GoogleTranslationProperties"
  50. }
  51. ],
  52. "hints": []
  53. }

四、测试

image.png