1. 概览

在编写 Spring Boot 应用程序时,将配置属性映射到 Java bean 上是非常有用的。但是,记录这些属性的最好方法是什么呢?

在本教程中,我们将探讨 Spring Boot Configuration Processor关联的 JSON 元数据文件,该 JSON 文档记录每个属性的含义、约束等。

2. 配置元数据

作为开发人员,我们开发的大多数应用程序在某种程度上必须是可配置的。但是在通常情况下,我们并不能够真正的理解配置参数的作用,比如它有默认值,又或者是过时的,有时我们甚至不知道该属性的存在。

为了帮助我们理清楚,Spring Boot 生成了配置元数据的 JSON 文件,为我们提供关于如何使用属性的有用信息。所以,配置元数据是一个描述性文件,它包含与配置属性交互所需的必要信息。

这个文件的真正好处是IDE也可以读取它,从而为我们自动配置完成Spring属性以及其他配置提示。

3. 依赖

为了生成此配置元数据,我们将使用 spring-boot-configuration-processor 的依赖.

因此,让我们继续将依赖项添加为可选依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.7.RELEASE</version>
<optional>true</optional>
</dependency>

这种依赖关系将为我们提供在构建项目时调用的 Java 注解处理器。我们稍后会详细讨论这个问题。

为了防止 @ConfigurationProperties 不应用于我们的项目使用的其他模块,在 Maven 中添加依赖项为可选依赖 是最好的做法。

4. 配置属性示例

现在来研究处理器是怎么工作的,我们需要使用 Java bean 获取在 Spring Boot 应用程序中包含一些属性:

@Configuration
@ConfigurationProperties(prefix = "database")
public class DatabaseProperties { public static class Server {
private String ip;
private int port; // standard getters and setters
} private String username;
private String password;
private Server server; // standard getters and setters
}

要做到这一点,我们可以使用 @ConfigurationProperties 注解。配置处理器会扫描使用了此注解的类和方法,用来访问配置参数并生成配置元数据。

让我们将这些属性添加到属性文件中。在示例中,我们把文件命名为 databaseproperties-test.properties

#Simple Properties
database.username=baeldung
database.password=password

我们还将添加一个测试,以确保我们都做对了:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = AnnotationProcessorApplication.class)
@TestPropertySource("classpath:databaseproperties-test.properties")
public class DatabasePropertiesIntegrationTest { @Autowired
private DatabaseProperties databaseProperties; @Test
public void whenSimplePropertyQueriedThenReturnsPropertyValue()
throws Exception {
Assert.assertEquals("Incorrectly bound Username property",
"baeldung", databaseProperties.getUsername());
Assert.assertEquals("Incorrectly bound Password property",
"password", databaseProperties.getPassword());
} }

我们通过内部类 Server 还添加了嵌套属性 database.server.iddatabase.server.port我们应该添加内部类 Server 以及一个 server 的属性并且生成他的 getter 和 setter 方法。

在我们的测试中,让我们快速检查一下,确保我们也可以成功地设置和读取嵌套属性:

@Test
public void whenNestedPropertyQueriedThenReturnsPropertyValue()
throws Exception {
Assert.assertEquals("Incorrectly bound Server IP nested property",
"127.0.0.1", databaseProperties.getServer().getIp());
Assert.assertEquals("Incorrectly bound Server Port nested property",
3306, databaseProperties.getServer().getPort());
}

好了,现在我们准备使用处理器了。

5. 生成配置元数据

我们在前面提到过,配置处理器生成一个文件 – 它是使用注解处理实现的。

所以,在项目编译之后,我们将在目录 target/classes/META-INF 下看到文件名为 spring-configuration-metadata.json 的文件:

{
"groups": [
{
"name": "database",
"type": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties",
"sourceType": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties"
},
{
"name": "database.server",
"type": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties$Server",
"sourceType": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties",
"sourceMethod": "getServer()"
}
],
"properties": [
{
"name": "database.password",
"type": "java.lang.String",
"sourceType": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties"
},
{
"name": "database.server.ip",
"type": "java.lang.String",
"sourceType": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties$Server"
},
{
"name": "database.server.port",
"type": "java.lang.Integer",
"sourceType": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties$Server",
"defaultValue": 0
},
{
"name": "database.username",
"type": "java.lang.String",
"sourceType": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties"
}
],
"hints": []
}

接下来,让我们看看更改 Java bean 上的注解如何影响元数据。

5.1. 关于配置元数据的其他信息

首先,让我们将 JavaDoc 注释添加到 Server 上.

第二,让我们给出一个 database.server.port 字段的默认值并最后添加 @Min@Max 注解:

public static class Server {

    /**
* The IP of the database server
*/
private String ip; /**
* The Port of the database server.
* The Default value is 443.
* The allowed values are in the range 400-4000.
*/
@Min(400)
@Max(800)
private int port = 443; // standard getters and setters
}

如果我们检查 spring-configuration-metadata.json 文件,我们将看到这些额外的信息得到了反映:

{
"groups": [
{
"name": "database",
"type": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties",
"sourceType": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties"
},
{
"name": "database.server",
"type": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties$Server",
"sourceType": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties",
"sourceMethod": "getServer()"
}
],
"properties": [
{
"name": "database.password",
"type": "java.lang.String",
"sourceType": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties"
},
{
"name": "database.server.ip",
"type": "java.lang.String",
"description": "The IP of the database server",
"sourceType": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties$Server"
},
{
"name": "database.server.port",
"type": "java.lang.Integer",
"description": "The Port of the database server. The Default value is 443.
The allowed values are in the range 400-4000",
"sourceType": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties$Server",
"defaultValue": 443
},
{
"name": "database.username",
"type": "java.lang.String",
"sourceType": "com.baeldung.autoconfiguration.annotationprocessor.DatabaseProperties"
}
],
"hints": []
}

我们可以找到 database.server.ipdatabase.server.port 属性的不同之处。事实上,额外的信息是非常有帮助的。开发人员和 IDE 都更容易理解每个属性的功能。

我们还应该确保触发构建以获得更新的文件。在Eclipse中,如果选中“自动构建”选项,则每个保存操作都会触发一次构建。在 IntelliJ 中,我们应该手动触发构建。

5.2. 理解元数据格式

让我们仔细看看 JSON 元数据文件,并讨论其组成。

Groups 是用于分组其他属性的较高级别的项,而不指定值本身。在我们的例子中,我们有数据库组,它也是配置属性的前缀。我们还有一个 database 组,它是通过内部类把 IPport 属性作为一个组。

属性是可以为其指定值的配置项。这些属性配置在后缀为 *.properties或 .yml 文件中,并且可以有额外的信息,比如默认值和验证,就像我们在上面的示例中看到的那样。

提示是帮助用户设置属性值的附加信息。例如,如果我们有一组属性的允许值,我们可以提供每个属性的描述。IDE 将为这些提示提供自动选择的帮助。

配置元数据上的每个组成都有自己的属性。来解释配置属性的详细用法。

6. 总结

在本文中,我们介绍了 Spring Boot 配置处理器及其创建配置元数据的功能。使用此元数据可以更轻松地与配置参数进行交互。

我们给出了一个生成的配置元数据的示例,并详细解释了它的格式和组成。

我们还看到了 IDE 上的自动完成支持是多么有帮助。

与往常一样,本文中提到的所有代码片段都可以在我们的 GitHub 存储库找到。

原文:https://www.baeldung.com/spring-boot-configuration-metadata

作者:Dionis Prifti

译者:遗失的拂晓

Spring Boot 配置元数据指南的更多相关文章

  1. Spring Boot -- 配置切换指南

    一般在一个项目中,总是会有好多个环境.比如: 开发环境 -> 测试环境 -> 预发布环境 -> 生产环境 每个环境上的配置文件总是不一样的,甚至开发环境中每个开发者的环境可能也会有一 ...

  2. Spring Boot 配置优先级顺序

    一般在一个项目中,总是会有好多个环境.比如: 开发环境 -> 测试环境 -> 预发布环境 -> 生产环境 每个环境上的配置文件总是不一样的,甚至开发环境中每个开发者的环境可能也会有一 ...

  3. spring boot 配置注入

    spring boot配置注入有变量方式和类方式(参见:<spring boot 自定义配置属性的各种方式>),变量中又要注意静态变量的注入(参见:spring boot 给静态变量注入值 ...

  4. Spring boot配置多个Redis数据源操作实例

    原文:https://www.jianshu.com/p/c79b65b253fa Spring boot配置多个Redis数据源操作实例 在SpringBoot是项目中整合了两个Redis的操作实例 ...

  5. spring boot配置springMVC拦截器

    spring boot通过配置springMVC拦截器 配置拦截器比较简单, spring boot配置拦截器, 重写preHandle方法. 1.配置拦截器: 2重写方法 这样就实现了拦截器. 其中 ...

  6. spring boot配置mybatis和事务管理

    spring boot配置mybatis和事务管理 一.spring boot与mybatis的配置 1.首先,spring boot 配置mybatis需要的全部依赖如下: <!-- Spri ...

  7. [转] Spring Boot配置多个DataSource

    [From]  https://www.liaoxuefeng.com/article/001484212576147b1f07dc0ab9147a1a97662a0bd270c20000 Sprin ...

  8. Spring boot 配置异步处理执行器

    示例如下: 1. 新建Maven 项目 async-executor 2.pom.xml <project xmlns="http://maven.apache.org/POM/4.0 ...

  9. Spring boot配置404、500页面

    Spring boot 配置404页面很简单,如果你访问的url没有找到就会出现spring boot 提示的页面,很明显Spring boot不用配置就可以显示404页面了. 在template下创 ...

随机推荐

  1. getline()与get()(c++学习笔记)

    istream中的类(如cin)提供了一些面向行的类成员函数:getline()和get() 1.getline()函数 读取整行,使用回车键输入的换行符来确定输入结尾. 调用方法:cin.getli ...

  2. Go 面试每天一篇(第 1 天)

    下面这段代码输出的内容 package main import ( "fmt" ) func main() { defer_call() } func defer_call() { ...

  3. 使用mybatis-generator生成底层

    使用mybatis-generator生成底层 前言 ​ 使用springboot2,jdk1.8,idea 一.在pom引入相关依赖 <!--mybatise-generator--> ...

  4. mac入门之设置

    mac入门: 一般手机软件,都是分设置和业务功能:操作系统亦是如此,设置+必备应用:用设置入门十分合理. 总览: 通用:通用,顾明思意是设置的设置,设置是独立应用之外或者公共的开关,通用更抽象一层,没 ...

  5. effective java 3th item2:考虑 builder 模式,当构造器参数过多的时候

    yiaz 读书笔记,翻译于 effective java 3th 英文版,可能有些地方有错误.欢迎指正. 静态工厂方法和构造器都有一个限制:当有许多参数的时候,它们不能很好的扩展. 比如试想下如下场景 ...

  6. 牛客2018多校第五场E-room 最小费用最大流

    题意:有n个寝室,每个寝室4个人,现在在搞搬寝室的活动,告诉你每个寝室之前的人员名单,和之后的人员名单,问最少需要几个人要搬寝室. 思路: 转化为最小费用最大流解决的二分图问题,对每个去年的宿舍,向每 ...

  7. CF1025C Plasticine zebra 思维 字符串

    Plasticine zebra time limit per test 1 second memory limit per test 256 megabytes input standard inp ...

  8. 牛客网 湖南大学2018年第十四届程序设计竞赛重现赛 A game

    链接:https://www.nowcoder.com/acm/contest/125/A来源:牛客网 Tony and Macle are good friends. One day they jo ...

  9. 线段树模板 hdu 1166 敌兵布阵

    敌兵布阵 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submis ...

  10. Unity3D 客户端编程

    Photon Server 和 Unity3D 数据交互: Photon Server 服务端编程 Unity3D 客户端编程. VS2017 之 MYSQL实体数据模 1:打开unity新建新项目, ...