Using application.yml vs application.properties in Spring Boot – 在Spring Boot中使用application.yml与application.properties

最后修改: 2020年 8月 22日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

A common practice in Spring Boot is using an external configuration to define our properties. This allows us to use the same application code in different environments.

Spring Boot 的一个常见做法是使用外部配置来定义我们的属性。这使我们能够在不同的环境中使用相同的应用程序代码。

We can use properties files, YAML files, environment variables and command-line arguments.

我们可以使用属性文件、YAML文件、环境变量和命令行参数。

In this short tutorial, we’ll explore the main differences between properties and YAML files.

在这个简短的教程中,我们将探讨属性和YAML文件的主要区别。

2. Properties Configuration

2.属性配置

By default, Spring Boot can access configurations set in an application.properties file, which uses a key-value format:

默认情况下,Spring Boot可以访问application.properties文件中设置的配置,该文件使用键值格式。

spring.datasource.url=jdbc:h2:dev
spring.datasource.username=SA
spring.datasource.password=password

Here each line is a single configuration, so we need to express hierarchical data by using the same prefixes for our keys. And in this example, every key belongs to spring.datasource.

在这里,每一行都是一个单独的配置,所以我们需要通过对我们的键使用相同的前缀来表达分层的数据。而在这个例子中,每个键都属于spring.datasource

2.1. Placeholders in Properties

2.1.属性中的占位符

Within our values, we can use placeholders with the ${} syntax to refer to the contents of other keys, system properties, or environment variables:

在我们的值中,我们可以使用带有${}语法的占位符来引用其他键、系统属性或环境变量的内容。

app.name=MyApp
app.description=${app.name} is a Spring Boot application

2.2. List Structure

2.2.列表结构

If we have the same kind of properties with different values, we can represent the list structure with array indices:

如果我们有相同种类的属性,但数值不同,我们可以用数组索引表示列表结构。

application.servers[0].ip=127.0.0.1
application.servers[0].path=/path1
application.servers[1].ip=127.0.0.2
application.servers[1].path=/path2
application.servers[2].ip=127.0.0.3
application.servers[2].path=/path3

2.3. Multiple Profiles

2.3.多个配置文件

Since version 2.4.0, Spring Boot supports creating multi-document properties files. Simply put, we can split a single physical file into multiple logical documents.

从2.4.0版本开始,Spring Boot支持创建多文档属性文件。简单地说,我们可以把一个物理文件分成多个逻辑文件。

This allows us to define a document for each profile we need to declare, all in the same file:

这使我们能够为我们需要声明的每个配置文件定义一个文件,都在同一个文件中。

logging.file.name=myapplication.log
bael.property=defaultValue
#---
spring.config.activate.on-profile=dev
spring.datasource.password=password
spring.datasource.url=jdbc:h2:dev
spring.datasource.username=SA
bael.property=devValue
#---
spring.config.activate.on-profile=prod
spring.datasource.password=password
spring.datasource.url=jdbc:h2:prod
spring.datasource.username=prodUser
bael.property=prodValue

Note we use the ‘#—‘ notation to indicate where we want to split the document.

请注意,我们使用 “#—-“符号来表示我们想要分割文件的地方。

In this example, we have two spring sections with different profiles tagged. Also, we can have a common set of properties at the root level — in this case, the logging.file.name property will be the same in all profiles.

在这个例子中,我们有两个spring部分,有不同的profiles标签。另外,我们可以在根层有一套共同的属性–在这种情况下,logging.file.name属性在所有配置文件中都是一样的。

2.4. Profiles Across Multiple Files

2.4.跨越多个文件的配置文件

As an alternative to having different profiles in the same file, we can store multiple profiles across different files. Prior to version 2.4.0, this was the only method available for properties files.

作为同一文件中不同配置文件的替代方案,我们可以在不同文件中存储多个配置文件。在2.4.0版本之前,这是唯一可用于properties文件的方法。

We achieve this by putting the name of the profile in the file name — for example, application-dev.yml or application-dev.properties.

我们通过将配置文件的名称放在文件名中来实现这一点–例如,application-dev.yml application-dev.properties

3. YAML Configuration

3.YAML配置

3.1. YAML Format

3.1 YAML格式

As well as Java properties files, we can also use YAML-based configuration files in our Spring Boot application. YAML is a convenient format for specifying hierarchical configuration data.

除了 Java 属性文件外,我们还可以在 Spring Boot 应用程序中使用基于 YAML 的配置文件。YAML是一种用于指定分层配置数据的方便格式。

Now let’s take the same example from our properties file and convert it to YAML:

现在让我们从我们的属性文件中抽取同样的例子,并将其转换为YAML。

spring:
    datasource:
        password: password
        url: jdbc:h2:dev
        username: SA

This can be more readable than its property file alternative since it does not contain repeated prefixes.

这可能比其属性文件的替代方案更易读,因为它不包含重复的前缀。

3.2. List Structure

3.2.列表结构

YAML has a more concise format for expressing lists:

YAML 有一个更简洁的格式来表达列表。

application:
    servers:
    -   ip: '127.0.0.1'
        path: '/path1'
    -   ip: '127.0.0.2'
        path: '/path2'
    -   ip: '127.0.0.3'
        path: '/path3'

3.3. Multiple Profiles

3.3.多个配置文件

Unlike properties files, YAML supports multi-document files by design, and this way, we can store multiple profiles in the same file no matter which version of Spring Boot we use.

与属性文件不同,YAML在设计上支持多文档文件,这样一来,无论我们使用哪个版本的Spring Boot,都可以在同一个文件中存储多个配置文件。

In this case, however, the spec indicates we have to use three dashes to indicate the start of a new document:

然而,在这种情况下,规范指出我们必须使用三个破折号来表示一个新文件的开始

logging:
  file:
    name: myapplication.log
---
spring:
  config:
    activate:
      on-profile: staging
  datasource:
    password: 'password'
    url: jdbc:h2:staging
    username: SA
bael:
  property: stagingValue

Note: We usually don’t want to include both the standard application.properties and the application.yml files in our project at the same time, as it could lead to unexpected results.

注意:我们通常不想在项目中同时包含标准的application.propertiesapplication.yml文件,因为这可能导致意想不到的结果。

For instance, if we combine the properties shown above (in an application.yml file) with the properties described in Section 2.3., then bael.property would be assigned with defaultValue instead of with the profile-specific value. This is simply because the application.properties are loaded later on, overriding the values assigned up to that point.

例如,如果我们将上面显示的属性(在 application.yml 文件中)与第 2.3 节中描述的属性结合起来,那么 bael.property 将被分配为 defaultValue,而不是特定的配置文件值。这只是因为application.properties稍后被加载,覆盖了到那时为止的分配值。

4. Spring Boot Usage

4.Spring Boot的使用方法

Now that we’ve defined our configurations, let’s see how to access them.

现在我们已经定义了我们的配置,让我们看看如何访问它们。

4.1. Value Annotation

4.1.价值注释

We can inject the values of our properties using the @Value annotation:

我们可以使用@Value注解注入我们的属性值。

@Value("${key.something}")
private String injectedProperty;

Here the property key.something is injected via field injection into one of our objects.

这里,属性key.something通过字段注入被注入到我们的一个对象中。

4.2. Environment Abstraction

4.2.环境抽象

We can also obtain the value of a property using the Environment API:

我们还可以使用Environment API来获得一个属性的值。

@Autowired
private Environment env;

public String getSomeKey(){
    return env.getProperty("key.something");
}

4.3. ConfigurationProperties Annotation

4.3.ConfigurationProperties注释

Finally, we can also use the @ConfigurationProperties annotation to bind our properties to type-safe structured objects:

最后,我们还可以使用@ConfigurationProperties注解,将我们的属性绑定到类型安全的结构化对象。

@ConfigurationProperties(prefix = "mail")
public class ConfigProperties {
    String name;
    String description;
...

5. Conclusion

5.总结

In this article, we’ve seen some differences between properties and yml Spring Boot configuration files. We also saw how their values could refer to other properties. Finally, we looked at how to inject the values into our runtime.

在这篇文章中,我们看到了propertiesyml Spring Boot配置文件之间的一些区别。我们还看到了它们的值是如何引用其他属性的。最后,我们研究了如何将这些值注入到我们的运行时中。

As always, all the code examples are available over on GitHub.

一如既往,所有的代码实例都可以在GitHub上找到