Properties and Configuration

本部分包含有关设置和读取属性和配置设置及其与 Spring Boot 应用程序交互的主题。

This section includes topics about setting and reading properties and configuration settings and their interaction with Spring Boot applications.

Automatically Expand Properties at Build Time

与其硬编码项目构建配置中也指定的一些属性,你可以通过改为使用现有的构建配置来自动扩展它们。这在 Maven 和 Gradle 中都是可能的。

Rather than hardcoding some properties that are also specified in your project’s build configuration, you can automatically expand them by instead using the existing build configuration. This is possible in both Maven and Gradle.

Automatic Property Expansion Using Maven

你可以通过使用资源过滤来自动扩展 Maven 项目中的属性。如果你使用 spring-boot-starter-parent,则可以参考具有 @..@ 占位符的 Maven“项目属性”,如下面的示例所示:

You can automatically expand properties from the Maven project by using resource filtering. If you use the spring-boot-starter-parent, you can then refer to your Maven '`project properties’ with @..@ placeholders, as shown in the following example:

app:
  encoding: "@project.build.sourceEncoding@"
  java:
    version: "@java.version@"

仅以这种方式过滤生产品配置(换句话说,“src/test/resources” 上未应用任何过滤)。

Only production configuration is filtered that way (in other words, no filtering is applied on src/test/resources).

如果你启用“addResources”标志,“spring-boot:run”目标可以直接将“src/main/resources”添加到类路径中(出于热重载目的)。这样做可以绕开资源过滤和该功能。相反,你可以使用“exec:java”目标或自定义插件的配置。请参阅 plugin usage page 了解详情。

If you enable the addResources flag, the spring-boot:run goal can add src/main/resources directly to the classpath (for hot reloading purposes). Doing so circumvents the resource filtering and this feature. Instead, you can use the exec:java goal or customize the plugin’s configuration. See the plugin usage page for more details.

如果你未使用启动器父级,则需要在“pom.xml”的“<build/>”元素内包含以下元素:

If you do not use the starter parent, you need to include the following element inside the <build/> element of your pom.xml:

<resources>
	<resource>
		<directory>src/main/resources</directory>
		<filtering>true</filtering>
	</resource>
</resources>

你还需要在“<plugins/>”内包含以下元素:

You also need to include the following element inside <plugins/>:

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-resources-plugin</artifactId>
	<version>2.7</version>
	<configuration>
		<delimiters>
			<delimiter>@</delimiter>
		</delimiters>
		<useDefaultDelimiters>false</useDefaultDelimiters>
	</configuration>
</plugin>

如果你在配置中使用了标准 Spring 占位符(例如 ${placeholder}),则“useDefaultDelimiters”属性非常重要。如果该属性未设置为 false,则这些属性可以通过构建进行扩展。

The useDefaultDelimiters property is important if you use standard Spring placeholders (such as ${placeholder}) in your configuration. If that property is not set to false, these may be expanded by the build.

Automatic Property Expansion Using Gradle

你可以通过如以下示例所示配置 Java 插件的 processResources 任务来自动扩展 gradle 项目中的属性:

You can automatically expand properties from the Gradle project by configuring the Java plugin’s processResources task to do so, as shown in the following example:

tasks.named('processResources') {
	expand(project.properties)
}

然后,你可以使用占位符来引用 Gradle 项目的属性,如以下示例所示:

You can then refer to your Gradle project’s properties by using placeholders, as shown in the following example:

app:
  name: "${name}"
  description: "${description}"

Gradle 的 expand 方法使用 Groovy 的 SimpleTemplateEngine,它转换 ${..} 令牌。“${..}”的样式与 Spring 本身的属性占位符机制相冲突。若要将 Spring 的属性占位符与自动扩展结合使用,请按以下方式转义 Spring 的属性占位符:\${..}

Gradle’s expand method uses Groovy’s SimpleTemplateEngine, which transforms ${..} tokens. The ${..} style conflicts with Spring’s own property placeholder mechanism. To use Spring property placeholders together with automatic expansion, escape the Spring property placeholders as follows: \${..}.

Externalize the Configuration of SpringApplication

SpringApplication”具有 Bean 属性设置器,因此你可以在创建应用程序时使用其 Java API 来修改其行为。或者,你可以通过在 spring.main.* 中设置属性来将配置外置化。例如,在 application.properties 中,你可能具有以下设置:

A SpringApplication has bean property setters, so you can use its Java API as you create the application to modify its behavior. Alternatively, you can externalize the configuration by setting properties in spring.main.*. For example, in application.properties, you might have the following settings:

spring:
  main:
    web-application-type: "none"
    banner-mode: "off"

然后,Spring Boot 横幅不会在启动时打印出来,并且该应用程序不会启动嵌入式 Web 服务器。

Then the Spring Boot banner is not printed on startup, and the application is not starting an embedded web server.

在外部配置中定义的属性替代和替换使用 Java API 指定的值,显着的例外是主源。主源是提供给 SpringApplication 构造函数的值:

Properties defined in external configuration override and replace the values specified with the Java API, with the notable exception of the primary sources. Primary sources are those provided to the SpringApplication constructor:

或者提供给“SpringApplicationBuilder”的“sources(…​)”方法:

Or to sources(…​) method of a SpringApplicationBuilder:

根据以上示例,如果我们具有以下配置:

Given the examples above, if we have the following configuration:

spring:
  main:
    sources: "com.example.MyDatabaseConfig,com.example.MyJmsConfig"
    banner-mode: "console"

实际应用程序将显示横幅(由配置替代)并使用三个源获取 ApplicationContext。应用程序源为:

The actual application will show the banner (as overridden by configuration) and uses three sources for the ApplicationContext. The application sources are:

  1. MyApplication (from the code)

  2. MyDatabaseConfig (from the external config)

  3. MyJmsConfig(from the external config)

Change the Location of External Properties of an Application

默认情况下,来自不同源的属性按定义的顺序添加到 Spring Environment 中(请参阅“Spring Boot 功能章节”中的`“Externalized Configuration”`,了解确切的顺序)。

By default, properties from different sources are added to the Spring Environment in a defined order (see “Externalized Configuration” in the '`Spring Boot features’ section for the exact order).

你还可以提供以下系统属性(或环境变量)来更改行为:

You can also provide the following System properties (or environment variables) to change the behavior:

  • configprop:spring.config.name[] (configprop:spring.config.name[format=envvar]): Defaults to application as the root of the file name.

  • configprop:spring.config.location[] (configprop:spring.config.location[format=envvar]): The file to load (such as a classpath resource or a URL). A separate Environment property source is set up for this document and it can be overridden by system properties, environment variables, or the command line.

无论在环境中设置了什么,Spring Boot 始终加载如上所述的 application.properties。默认情况下,如果使用 YAML,则扩展名为 “.yaml’ 和 “.yml’ 的文件还会添加到此列表中。

No matter what you set in the environment, Spring Boot always loads application.properties as described above. By default, if YAML is used, then files with the '`.yaml’ and '`.yml’ extension are also added to the list.

如果您想要有关所加载文件的详细信息,可以 set the logging level org.springframework.boot.context.configtrace

If you want detailed information about the files that are being loaded you can set the logging level of org.springframework.boot.context.config to trace.

Use '`Short’ Command Line Arguments

有些人喜欢使用 (例如) --port=9000 代替 --server.port=9000 在命令行上设置配置属性。您可以使用 application.properties 中的占位符来启用此行为,如下例所示:

Some people like to use (for example) --port=9000 instead of --server.port=9000 to set configuration properties on the command line. You can enable this behavior by using placeholders in application.properties, as shown in the following example:

server:
  port: "${port:8080}"

如果您从 spring-boot-starter-parent POM 继承,maven-resources-plugins 的默认筛选令牌已从 ${*} 更改为 @(即,@maven.token@ 代替 ${maven.token}),以防止与 Spring 风格占位符产生冲突。如果您已直接为 application.properties 启用了 Maven 筛选,您可能还想将默认筛选令牌更改为使用 other delimiters

If you inherit from the spring-boot-starter-parent POM, the default filter token of the maven-resources-plugins has been changed from ${*} to @ (that is, @maven.token@ instead of ${maven.token}) to prevent conflicts with Spring-style placeholders. If you have enabled Maven filtering for the application.properties directly, you may want to also change the default filter token to use other delimiters.

在此特定情况下,端口绑定适用于 PaaS 环境,例如 Heroku 或 Cloud Foundry。在这两个平台中,PORT 环境变量会自动设置,Spring 可以绑定到 Environment 属性的大写同义词。

In this specific case, the port binding works in a PaaS environment such as Heroku or Cloud Foundry. In those two platforms, the PORT environment variable is set automatically and Spring can bind to capitalized synonyms for Environment properties.

Use YAML for External Properties

YAML 是 JSON 的超集,因此是个方便的语法,用于以分层格式存储外部属性,如下例所示:

YAML is a superset of JSON and, as such, is a convenient syntax for storing external properties in a hierarchical format, as shown in the following example:

spring:
  application:
    name: "cruncher"
  datasource:
    driver-class-name: "com.mysql.jdbc.Driver"
    url: "jdbc:mysql://localhost/test"
server:
  port: 9000

创建一个名为 application.yaml 的文件并将其放在类路径的根目录中。然后将 snakeyaml 添加到您的依赖项中(Maven 坐标 org.yaml:snakeyaml,如果您使用 spring-boot-starter 已包括在内)。YAML 文件被解析为 Java Map<String,Object>(就像 JSON 对象一样),Spring Boot 将该映射展平,使其只有一级深度并带有以句点分隔的键,正如许多人习惯在 Java 中使用 Properties 文件那样。

Create a file called application.yaml and put it in the root of your classpath. Then add snakeyaml to your dependencies (Maven coordinates org.yaml:snakeyaml, already included if you use the spring-boot-starter). A YAML file is parsed to a Java Map<String,Object> (like a JSON object), and Spring Boot flattens the map so that it is one level deep and has period-separated keys, as many people are used to with Properties files in Java.

前面的示例 YAML 对应于以下 application.properties 文件:

The preceding example YAML corresponds to the following application.properties file:

spring.application.name=cruncher
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/test
server.port=9000

有关 YAML 的更多信息,请参见“Spring Boot 特性”部分中的 “Working With YAML”。

See “Working With YAML” in the '`Spring Boot features’ section for more information about YAML.

Set the Active Spring Profiles

Spring Environment 有一个与此相关的 API,但通常您会设置一个系统属性 (configprop:spring.profiles.active[]) 或一个操作系统环境变量 (configprop:spring.profiles.active[format=envvar])。此外,您可以使用 -D 参数启动应用程序(记住将其放在主类或 jar 存档之前),如下所示:

The Spring Environment has an API for this, but you would normally set a System property (configprop:spring.profiles.active[]) or an OS environment variable (configprop:spring.profiles.active[format=envvar]). Also, you can launch your application with a -D argument (remember to put it before the main class or jar archive), as follows:

$ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar

在 Spring Boot 中,您还可以在 application.properties 中设置活动概要文件,如下例所示:

In Spring Boot, you can also set the active profile in application.properties, as shown in the following example:

spring:
  profiles:
    active: "production"

此方式设置的值不会被系统属性或环境变量设置替换,但会被 SpringApplicationBuilder.profiles() 方法替换。因此,后一个 Java API 可用于增加概要文件而不更改默认设置。

A value set this way is replaced by the System property or environment variable setting but not by the SpringApplicationBuilder.profiles() method. Thus, the latter Java API can be used to augment the profiles without changing the defaults.

有关更多信息,请参见 “Spring Boot features” 部分中的 “Profiles”。

See “Profiles” in the “Spring Boot features” section for more information.

Set the Default Profile Name

默认概要文件是指在没有活动概要文件时启用的概要文件。默认情况下,默认概要文件的名称是 default,但可以使用系统属性 (configprop:spring.profiles.default[]) 或操作系统环境变量 (configprop:spring.profiles.default[format=envvar]) 进行更改。

The default profile is a profile that is enabled if no profile is active. By default, the name of the default profile is default, but it could be changed using a System property (configprop:spring.profiles.default[]) or an OS environment variable (configprop:spring.profiles.default[format=envvar]).

在 Spring Boot 中,您还可以在 application.properties 中设置默认概要文件名,如下例所示:

In Spring Boot, you can also set the default profile name in application.properties, as shown in the following example:

spring:
  profiles:
    default: "dev"

有关更多信息,请参见 “Spring Boot features” 部分中的 “Profiles”。

See “Profiles” in the “Spring Boot features” section for more information.

Change Configuration Depending on the Environment

Spring Boot 支持多文档 YAML 和 Properties 文件(有关详细信息,请参见 Working With Multi-Document Files),它们可以根据活动概要文件有条件地激活。

Spring Boot supports multi-document YAML and Properties files (see Working With Multi-Document Files for details) which can be activated conditionally based on the active profiles.

如果文档包含 spring.config.activate.on-profile 键,则将概要文件值(由概要文件或概要文件表达式组成的逗号分隔列表)馈送到 Spring Environment.acceptsProfiles() 方法中。如果概要文件表达式匹配,则该文档将包含在最终合并中(如果不是,则不包含),如下例所示:

If a document contains a spring.config.activate.on-profile key, then the profiles value (a comma-separated list of profiles or a profile expression) is fed into the Spring Environment.acceptsProfiles() method. If the profile expression matches then that document is included in the final merge (otherwise, it is not), as shown in the following example:

server:
  port: 9000
---
spring:
  config:
    activate:
      on-profile: "development"
server:
  port: 9001
---
spring:
  config:
    activate:
      on-profile: "production"
server:
  port: 0

在上一个示例中,默认端口是 9000。但是,如果 Spring 配置文件称为“`development’”处于活动状态,则端口为 9001。如果“`production’”处于活动状态,则端口为 0。

In the preceding example, the default port is 9000. However, if the Spring profile called '`development’ is active, then the port is 9001. If '`production’ is active, then the port is 0.

文档按遇到的顺序合并。后面的值会覆盖前面的值。

The documents are merged in the order in which they are encountered. Later values override earlier values.

Discover Built-in Options for External Properties

Spring Boot 会在运行时将外部属性从 application.properties(或 YAML 文件和其它位置)绑定到应用程序中。一个位置不会(在技术上不可能)出现一个所有受支持属性的详尽列表,因为贡献可以来自类路径上的附加 jar 文件。

Spring Boot binds external properties from application.properties (or YAML files and other places) into an application at runtime. There is not (and technically cannot be) an exhaustive list of all supported properties in a single location, because contributions can come from additional jar files on your classpath.

一个具有 Actuator 特性的正在运行的应用程序有一个 configprops 端点,它显示通过 @ConfigurationProperties 提供的所有已绑定和可绑定属性。

A running application with the Actuator features has a configprops endpoint that shows all the bound and bindable properties available through @ConfigurationProperties.

附录包含一个 application.properties 示例,其中包含 Spring Boot 支持的最常见属性的列表。最终列表来自对 @ConfigurationProperties@Value 注释以及偶尔使用 Binder 的源代码进行搜索。有关加载属性的确切顺序的更多信息,请参见“Externalized Configuration”。

The appendix includes an application.properties example with a list of the most common properties supported by Spring Boot. The definitive list comes from searching the source code for @ConfigurationProperties and @Value annotations as well as the occasional use of Binder. For more about the exact ordering of loading properties, see "Externalized Configuration".