经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
SpringBoot 配置提示功能
来源:cnblogs  作者:逸飞兮  时间:2019/10/31 10:38:32  对本文有异议

提示

目的

配置自动提示的辅助功能可以让配置写起来更快,准确率大大提高。

springboot jar 包含提供所有支持的配置属性细节的元数据文件。文件的目的是为了让 IDE 开发者在用户使用 application.propertiesapplication.yml 文件时提供上下文帮助和代码补全。
大多数元数据文件是在编译时通过处理用 @ConfigurationProperties 注释的所有项自动生成的。也可以手动编写部分元数据。

版本

参考 SpringBoot 2.2.0.RELEASE 文档

文件

jar包中的 META-INF/spring-configuration-metadata.json (自动生成)或 META-INF/additional-spring-configuration-metadata.json (手动添加)

实战

  1. <!-- 引入相关依赖 -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-configuration-processor</artifactId>
  5. <optional>true</optional>
  6. </dependency>
  1. @Configuration
  2. @ConfigurationProperties(prefix = "file.upload")
  3. public class FileUploadConfig {
  4. /** Maximum number of bytes per file */
  5. private String maxSize = "1024M";
  6. /** 不允许的文件后缀 */
  7. private String rejectSuffix;
  8. //注意:使用的时候必须要有getter/setter,否则不会自动生成该属性对应的提示
  9. //此处因为篇幅原因省略 getter/setter
  10. }
  1. @Configuration
  2. @ConfigurationProperties("map.test")
  3. public class MapTestConfig {
  4. /** 测试Map类型数据的提示 */
  5. private Map<String, Object> data;
  6. //注意:使用的时候必须要有getter/setter,否则不会自动生成该属性对应的提示
  7. //此处因为篇幅原因省略 getter/setter
  8. }

中文注释会乱码,以上故意用中文注释的地方,会在下面文件中指定对应的描述,看是否会覆盖。

additional-spring-configuration-metadata.json

  1. {
  2. "properties": [
  3. {
  4. "name": "file.upload.reject-suffix",
  5. "type": "java.lang.String",
  6. "defaultValue": "exe,jar",
  7. "description": "The file suffix is not allowed.",
  8. "sourceType": "com.lw.metadata.config.FileUploadConfig"
  9. },
  10. {
  11. "name": "map.test.data",
  12. "type": "java.util.Map",
  13. "description": "Tips for testing Map type data.",
  14. "sourceType": "com.lw.metadata.config.MapTestConfig"
  15. }
  16. ],
  17. "hints": [
  18. {
  19. "name": "map.test.data.keys",
  20. "values": [
  21. {
  22. "value": "name",
  23. "description": "The name of the person."
  24. },
  25. {
  26. "value": "sex",
  27. "description": "The sex of the person."
  28. }
  29. ]
  30. }
  31. ]
  32. }

maven compile 之后,生成的 additional-spring-configuration-metadata.json 与源码中的一样,生成的 spring-configuration-metadata.json 如下:

  1. {
  2. "groups": [
  3. {
  4. "name": "file.upload",
  5. "type": "com.lw.metadata.config.FileUploadConfig",
  6. "sourceType": "com.lw.metadata.config.FileUploadConfig"
  7. },
  8. {
  9. "name": "map.test",
  10. "type": "com.lw.metadata.config.MapTestConfig",
  11. "sourceType": "com.lw.metadata.config.MapTestConfig"
  12. }
  13. ],
  14. "properties": [
  15. {
  16. "name": "file.upload.max-size",
  17. "type": "java.lang.String",
  18. "description": "Maximum number of bytes per file",
  19. "sourceType": "com.lw.metadata.config.FileUploadConfig",
  20. "defaultValue": "1024M"
  21. },
  22. {
  23. "name": "file.upload.reject-suffix",
  24. "type": "java.lang.String",
  25. "description": "The file suffix is not allowed.",
  26. "sourceType": "com.lw.metadata.config.FileUploadConfig",
  27. "defaultValue": "exe,jar"
  28. },
  29. {
  30. "name": "map.test.data",
  31. "type": "java.util.Map<java.lang.String,java.lang.Object>",
  32. "description": "Tips for testing Map type data.",
  33. "sourceType": "com.lw.metadata.config.MapTestConfig"
  34. }
  35. ],
  36. "hints": [
  37. {
  38. "name": "map.test.data.keys",
  39. "values": [
  40. {
  41. "value": "name",
  42. "description": "The name of the person."
  43. },
  44. {
  45. "value": "sex",
  46. "description": "The sex of the person."
  47. }
  48. ]
  49. }
  50. ]
  51. }

效果

SpringBoot配置提示效果

由此可以看到以下现象:

  • 代码中的默认值会自动生成到提示文件中,如:FileUploadConfig#maxSize
  • 代码中的注释会自动生成到提示文件中,如:FileUploadConfig#maxSize
  • additional-spring-configuration-metadata.json 文件中存在的提示会覆盖自动生成的对应属性,若自动生成的没有此属性则自动增加。

手动写提示文件

示例

  1. {
  2. "groups": [
  3. {
  4. "name": "server",
  5. "type": "org.springframework.boot.autoconfigure.web.ServerProperties",
  6. "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
  7. },
  8. {
  9. "name": "spring.jpa.hibernate",
  10. "type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate",
  11. "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties",
  12. "sourceMethod": "getHibernate()"
  13. }
  14. ],
  15. "properties": [
  16. {
  17. "name": "server.port",
  18. "type": "java.lang.Integer",
  19. "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
  20. },
  21. {
  22. "name": "server.address",
  23. "type": "java.net.InetAddress",
  24. "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties"
  25. },
  26. {
  27. "name": "spring.jpa.hibernate.ddl-auto",
  28. "type": "java.lang.String",
  29. "description": "DDL mode. This is actually a shortcut for the \"hibernate.hbm2ddl.auto\" property.",
  30. "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate"
  31. }
  32. ],
  33. "hints": [
  34. {
  35. "name": "spring.jpa.hibernate.ddl-auto",
  36. "values": [
  37. {
  38. "value": "none",
  39. "description": "Disable DDL handling."
  40. },
  41. {
  42. "value": "validate",
  43. "description": "Validate the schema, make no changes to the database."
  44. },
  45. {
  46. "value": "update",
  47. "description": "Update the schema if necessary."
  48. },
  49. {
  50. "value": "create",
  51. "description": "Create the schema and destroy previous data."
  52. },
  53. {
  54. "value": "create-drop",
  55. "description": "Create and then destroy the schema at the end of the session."
  56. }
  57. ]
  58. }
  59. ]
  60. }

groups

分组,将配置类分组。
可以按照文件来分组,即:将同一个配置文件的所有属性放在同一个组

属性 类型 是否必须 用途
name String Y 分组的完整名称
type String N 分组数据类型的类名(如:使用@ConfigurationProperties注释的完整类名、使用@Bean注释的方法返回类型)
description String N 分组的简短描述。
sourceType String N 提供分组来源的类名。
sourceMethod String N 提供分组的方法,包含括号和参数类型。

properties

提示主体,必须

属性 类型 是否必须 用途
name String Y 属性的完整名称。名称采用小写句点分隔格式,如:server.address
type String N 属性数据类型的完整签名(如:java.lang.String)或完整的泛型类型(如:java.util.Map<java.util.String,acme.Myenum>)。此属性提示用户输入值得类型。原生类型在此处使用其包装类型(如:boolean使用java.lang.Boolean)。
description String N 分组的简短描述。
sourceType String N 提供分组来源的类名。
defaultValue Object N 默认值。当属性为指定时使用。
deprecation Deprecation N 指定属性是否已弃用。

deprecation属性如下:

属性 类型 是否必须 用途
level String N 弃用级别,可以是 warning(默认值) 或 errorwarning:属性应该仍然可以使用;error:属性不保证可以使用
reason String N 属性弃用的简短原因。
replacement String N 替换此弃用属性的新属性全名。可为空

注意:Spring Boot 1.3 版本之前,是使用 boolean 类型的 deprecated

以下示例来源于官方文档,展示了如何处理这种场景:

  1. @ConfigurationProperties("app.acme")
  2. public class AcmeProperties {
  3. private String name;
  4. public String getName() { ... }
  5. public void setName(String name) { ... }
  6. @DeprecatedConfigurationProperty(replacement = "app.acme.name")
  7. @Deprecated
  8. public String getTarget() {
  9. return getName();
  10. }
  11. @Deprecated
  12. public void setTarget(String target) {
  13. setName(target);
  14. }
  15. }

一旦 getTargetsetTarget 方法从公共 API 中删除,元数据中的自动弃用提示也会消失。 如果要保留提示,则添加具有 error 弃用级别的手动元数据可以确保用户仍然了解该属性。在提供替代品时,这样做特别有用。

hints

辅助提示,非必须

属性 类型 是否必须 用途
name String Y 提示关联的属性的完整名称。名称是小写句点分隔格式(如:spring.mvc.servlet.path),如果属性关联map类型(如:system.contexts),提示可以关联map的键(system.contexts.keys)或者值(system.contexts.values)。
values ValueHint[] N 有效值集合。(下表详述)
providers ValueProvider[] N 提供者集合。(下表详述)

values 属性如下:

属性 类型 是否必须 用途
value Object Y 提示引用元素的有效值。如果属性是数组,value和description也可以是数组。
description String N value 对应的简短描述

### ValueHint

对于Map类型的支持如下:

  1. @ConfigurationProperties("sample")
  2. public class SampleProperties {
  3. private Map<String,Integer> contexts;
  4. // getters and setters
  5. }
  1. {"hints": [
  2. {
  3. "name": "sample.contexts.keys",
  4. "values": [
  5. {
  6. "value": "sample1"
  7. },
  8. {
  9. "value": "sample2"
  10. }
  11. ]
  12. }
  13. ]}

提示是对Map内每一对 key-value 的提示。

.keys.values 前缀必须分别关联 Map 的 keys 和 values。

providers 属性如下:

属性 类型 是否必须 用途
name String N 用于为提示所引用的元素提供其他内容帮助的 provider 的名称。
parameters JSON object N provider 所支持的任何其他参数(有关详细信息,请查看 provider 的文档)。

ValueProvider

一般用不到,建议跳过

下表总结了支持的 providers 列表:

属性 描述
any 允许提供任何附加值。
class-reference 自动完成项目中可用的类。通常由目标参数指定的基类约束。
handle-as 处理属性,就像它是由必须的 target 参数定义的类型定义的一样。
logger-name 自动完成有效的记录器名称和记录器组。通常,当前项目中可用的包和类名可以自动完成,也可以定义组。
spring-bean-reference 自动完成当前项目中可用的bean名称。通常由 target 参数指定的基类约束。
spring-profile-name 自动完成项目中可用的 spring 配置文件名称。

any

符合属性类型的所有值。

  1. {"hints": [
  2. {
  3. "name": "system.state",
  4. "values": [
  5. {
  6. "value": "on"
  7. },
  8. {
  9. "value": "off"
  10. }
  11. ],
  12. "providers": [
  13. {
  14. "name": "any"
  15. }
  16. ]
  17. }
  18. ]}

class-reference

提供以下参数:

参数 类型 默认值 描述
target String(Class) 分配给值的类的全限定类名。通常用于筛选非候选类。
concrete boolean true 指定是否仅将具体类视为有效候选。
  1. {"hints": [
  2. {
  3. "name": "server.servlet.jsp.class-name",
  4. "providers": [
  5. {
  6. "name": "class-reference",
  7. "parameters": {
  8. "target": "javax.servlet.http.HttpServlet"
  9. }
  10. }
  11. ]
  12. }
  13. ]}

handle-as

允许您将属性的类型替换为更高级的类型。

这通常在属性具有 java.lang.String 类型时发生,因为您不希望配置类依赖于不在类路径上的类。

参数 类型 默认值 描述
target String(Class) Y 为属性考虑的类型的完全限定名。

可用的值如下:

  • 任何 java.lang.Enum: 列出属性的可能值。
  • java.nio.charset.Charset: 支持自动完成字符集/编码值(如 utf-8
  • java.util.Locale:自动完成区域设置(如:en_US)
  • org.springframework.util.MimeType:支持自动完成 content-type 值(如:text/plain
  • org.springframework.core.io.Resource: 支持自动完成spring的资源抽象以引用文件系统或类路径上的文件 (如:classpath:/sample.properties

注意:如果要提供多个值,用 Collection 或 数组类型

  1. {"hints": [
  2. {
  3. "name": "spring.liquibase.change-log",
  4. "providers": [
  5. {
  6. "name": "handle-as",
  7. "parameters": {
  8. "target": "org.springframework.core.io.Resource"
  9. }
  10. }
  11. ]
  12. }
  13. ]}

logger-name

logger-name provider 自动完成有效的记录器名称和记录器组。 通常,当前项目中可用的包和类名可以自动完成。 如果组已启用(默认),并且配置中标识了自定义记录器组,则应提供该组的自动完成。

支持以下参数:

参数 类型 默认值 描述
group boolean true 指定是否应考虑已知组。

由于记录器名称可以是任意名称,此 provider 应允许任何值,但可以突出显示项目的类路径中不可用的有效包和类名。

以下是 logging.level 属性。keys 是 logger 名,values 关联标准的 log levels 或 自定义的 level,

  1. {"hints": [
  2. {
  3. "name": "logging.level.keys",
  4. "values": [
  5. {
  6. "value": "root",
  7. "description": "Root logger used to assign the default logging level."
  8. },
  9. {
  10. "value": "sql",
  11. "description": "SQL logging group including Hibernate SQL logger."
  12. },
  13. {
  14. "value": "web",
  15. "description": "Web logging group including codecs."
  16. }
  17. ],
  18. "providers": [
  19. {
  20. "name": "logger-name"
  21. }
  22. ]
  23. },
  24. {
  25. "name": "logging.level.values",
  26. "values": [
  27. {
  28. "value": "trace"
  29. },
  30. {
  31. "value": "debug"
  32. },
  33. {
  34. "value": "info"
  35. },
  36. {
  37. "value": "warn"
  38. },
  39. {
  40. "value": "error"
  41. },
  42. {
  43. "value": "fatal"
  44. },
  45. {
  46. "value": "off"
  47. }
  48. ],
  49. "providers": [
  50. {
  51. "name": "any"
  52. }
  53. ]
  54. }
  55. ]}

spring-bean-reference

此 provider 自动完成在当前项目的配置中定义的bean。 支持以下参数:

参数 类型 默认值 描述
target String(Class) 应该分配给候选对象的bean类的完全限定名。通常用于筛选非候选bean。

以下示例表示:spring.jmx.server 属性定义了使用 MBeanServer

  1. {"hints": [
  2. {
  3. "name": "spring.jmx.server",
  4. "providers": [
  5. {
  6. "name": "spring-bean-reference",
  7. "parameters": {
  8. "target": "javax.management.MBeanServer"
  9. }
  10. }
  11. ]
  12. }
  13. ]}

spring-profile-name

此 provider 自动完成在当前项目的配置中定义的spring配置文件。

以下示例表示:spring.profiles.active属性可启用的配置文件名称。

  1. {"hints": [
  2. {
  3. "name": "spring.profiles.active",
  4. "providers": [
  5. {
  6. "name": "spring-profile-name"
  7. }
  8. ]
  9. }
  10. ]}

可重复的元数据项

具有相同“property”和“group”名称的对象可以在元数据文件中多次出现。 例如,可以将两个单独的类绑定到同一前缀,每个类都有可能重叠的属性名。 虽然多次出现在元数据中的相同名称不应是常见的,但元数据的使用者应注意确保他们支持该名称。

自动生成提示文件

通过使用 spring-boot-configuration-processor jar,您可以从用 @ConfigurationProperties 注释的类中轻松生成自己的配置元数据文件。 jar包含一个java注释处理器,在编译项目时调用它。 用此处理器,需要引入 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>

处理器获取用@configurationproperties注释的类和方法。 配置类中字段值的 javadoc 用于填充 description 属性。

注意:仅仅只应将简单文本与@configurationproperties字段javadoc一起使用,因为在将它们添加到json之前不会对它们进行处理。

如果类有一个“至少一个参数”的构造函数,则为每个构造函数参数创建一个属性。 否则,通过标准getter和setter来发现属性,这些getter和setter对集合类型进行了特殊处理(即使只有getter存在,也会检测到)。

注解处理器还支持使用@data、@getter和@setter 的 lombok 注解。

注解处理器无法自动检测 EnumCollections 的默认值。在集合或枚举属性具有非空默认值的情况下,应提供手动元数据。

  1. @ConfigurationProperties(prefix="acme.messaging")
  2. public class MessagingProperties {
  3. private List<String> addresses = new ArrayList<>(Arrays.asList("a", "b")) ;
  4. private ContainerType = ContainerType.SIMPLE;
  5. // ... getter and setters
  6. public enum ContainerType {
  7. SIMPLE,
  8. DIRECT
  9. }
  10. }

为了提示上述属性的默认值,应该手动添加如下元数据:

  1. {"properties": [
  2. {
  3. "name": "acme.messaging.addresses",
  4. "defaultValue": ["a", "b"]
  5. },
  6. {
  7. "name": "acme.messaging.container-type",
  8. "defaultValue": "simple"
  9. }
  10. ]}

注意: 如果在项目中使用 AspectJ,则需要确保注解处理器只运行一次。 使用 Maven 时, 可以显式地配置 maven-apt-plugin插件,并仅在那里向注解处理器添加依赖项。 还可以让 AspectJ 插件运行于所有的处理且在 maven-compiler-pluginconfiguration 中禁用注解处理,如下:

  1. <plugin>
  2. <groupId>org.apache.maven.plugins</groupId>
  3. <artifactId>maven-compiler-plugin</artifactId>
  4. <configuration>
  5. <proc>none</proc>
  6. </configuration>
  7. </plugin>

绑定属性

注解处理器自动将内部类视为嵌套属性。

  1. @ConfigurationProperties(prefix="server")
  2. public class ServerProperties {
  3. private String name;
  4. private Host host;
  5. // ... getter and setters
  6. public static class Host {
  7. private String ip;
  8. private int port;
  9. // ... getter and setters
  10. }
  11. }

上述示例生成 server.nameserver.host.ipserver.host.port 属性的元数据信息。 可以在字段上使用@NestedconfigurationProperty 注解来指示应将常规(非内部)类视为嵌套类。

注意: 这对集合和映射没有影响,因为这些类型是自动标识的,并且为每个类型生成一个元数据属性。

添加额外的元数据

Spring Boot 的配置文件处理非常灵活,通常情况下,可能存在不绑定到 @ConfigurationProperties bean的属性。 您还可能需要调整现有key的某些属性,为了支持这种情况并让您提供自定义的“提示”,注解处理器会自动将 META-INF/additional-spring-configuration-metadata.json 中的提示项合并到主要元数据文件(spring-configuration-metadata.json)中

如果引用已自动检测到的属性,则将覆盖描述、默认值和弃用信息(如果指定)。 如果当前模块中没有标识手动属性中的声明,则将其作为新属性添加。

additional-spring-configuration-metadata.json 文件的格式与 spring-configuration-metadata.json 文件一样。 附加属性文件是可选的。如果没有任何其他属性,就不要添加文件。

参考资料

springboot 配置提示官方文档

原文链接:http://www.cnblogs.com/lw5946/p/11769298.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号