此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Boot 3.4.3! |
属性和配置
本节包括有关设置和读取属性和配置设置以及它们与 Spring Boot 应用程序的交互的主题。
在构建时自动扩展属性
您可以使用现有的构建配置来自动扩展这些属性,而不是对项目的构建配置中指定的某些属性进行硬编码。 这在 Maven 和 Gradle 中都是可能的。
使用 Maven 自动扩展属性
您可以使用资源筛选自动扩展 Maven 项目中的属性。
如果您使用spring-boot-starter-parent
,然后,您可以使用@..@
placeholders,如以下示例所示:
-
Properties
-
YAML
app:
encoding: "@project.build.sourceEncoding@"
java:
version: "@java.version@"
仅以这种方式过滤生产配置(换句话说,不应用过滤src/test/resources ). |
如果启用addResources flag 中,spring-boot:run goal 可以添加src/main/resources 直接发送到 Classpath (用于热重载目的)。
这样做会规避资源筛选和此功能。
相反,您可以使用exec:java goal 或自定义插件的配置。
有关更多详细信息,请参阅插件使用页面。 |
如果您不使用 starter 父级,则需要在<build/>
元素的pom.xml
:
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
您还需要在<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>
这useDefaultDelimiters 如果您使用标准的 Spring 占位符(例如${placeholder} ) 在您的配置中。
如果该属性未设置为false ,这些可能会通过构建进行扩展。 |
使用 Gradle 自动扩展属性
您可以通过配置 Java 插件的processResources
task 执行此作,如以下示例所示:
tasks.named('processResources') {
expand(project.properties)
}
然后,您可以使用占位符引用 Gradle 项目的属性,如以下示例所示:
-
Properties
-
YAML
app.name=${name}
app.description=${description}
app:
name: "${name}"
description: "${description}"
Gradle 的expand 方法使用 Groovy 的SimpleTemplateEngine ,它将${..} 令 牌。
这${..} style 与 Spring 自己的属性占位符机制冲突。
要将 Spring 属性占位符与自动扩展一起使用,请按如下方式转义 Spring 属性占位符:\${..} . |
外部化 SpringApplication 的配置
一个SpringApplication
具有 Bean 属性 setter,因此您可以在创建应用程序时使用其 Java API 来修改其行为。
或者,您可以通过在spring.main.*
.
例如,在application.properties
,您可能具有以下设置:
-
Properties
-
YAML
spring.main.web-application-type=none
spring.main.banner-mode=off
spring:
main:
web-application-type: "none"
banner-mode: "off"
然后,Spring Boot 横幅不会在启动时打印,并且应用程序不会启动嵌入式 Web 服务器。
在外部配置中定义的属性将覆盖并替换使用 Java API 指定的值,但主源除外。
主要来源是提供给SpringApplication
构造 函数:
-
Java
-
Kotlin
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}
}
import org.springframework.boot.Banner
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
object MyApplication {
@JvmStatic
fun main(args: Array<String>) {
val application = SpringApplication(MyApplication::class.java)
application.setBannerMode(Banner.Mode.OFF)
application.run(*args)
}
}
Or to sources(…)
method of a SpringApplicationBuilder
:
-
Java
-
Kotlin
import org.springframework.boot.Banner;
import org.springframework.boot.builder.SpringApplicationBuilder;
public class MyApplication {
public static void main(String[] args) {
new SpringApplicationBuilder()
.bannerMode(Banner.Mode.OFF)
.sources(MyApplication.class)
.run(args);
}
}
import org.springframework.boot.Banner
import org.springframework.boot.builder.SpringApplicationBuilder
object MyApplication {
@JvmStatic
fun main(args: Array<String>) {
SpringApplicationBuilder()
.bannerMode(Banner.Mode.OFF)
.sources(MyApplication::class.java)
.run(*args)
}
}
Given the examples above, if we have the following configuration:
-
Properties
-
YAML
spring.main.sources=com.example.MyDatabaseConfig,com.example.MyJmsConfig
spring.main.banner-mode=console
spring:
main:
sources: "com.example.MyDatabaseConfig,com.example.MyJmsConfig"
banner-mode: "console"
The actual application will show the banner (as overridden by configuration) and use three sources for the ApplicationContext
.
The application sources are:
-
MyApplication
(from the code)
-
MyDatabaseConfig
(from the external config)
-
MyJmsConfig
(from the external config)
Change the Location of External Properties of an Application
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:
-
spring.config.name
(SPRING_CONFIG_NAME
): Defaults to application
as the root of the file name.
-
spring.config.location
(SPRING_CONFIG_LOCATION
): 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.
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’ extensions are also added to the list.
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
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:
-
Properties
-
YAML
server.port=${port:8080}
server:
port: "${port:8080}"
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.
In this specific case, the port binding works in a PaaS environment such as Heroku or Cloud Foundry.
On 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 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
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.
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
See Working With YAML in the “Spring Boot Features” section for more information about YAML.
Set the Active Spring Profiles
The Spring Environment
has an API for this, but you would normally set a System property (spring.profiles.active
) or an OS environment variable (SPRING_PROFILES_ACTIVE
).
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
In Spring Boot, you can also set the active profile in application.properties
, as shown in the following example:
-
Properties
-
YAML
spring.profiles.active=production
spring:
profiles:
active: "production"
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.
See Profiles in the “Spring Boot Features” section for more information.
Set the Default Profile Name
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 (spring.profiles.default
) or an OS environment variable (SPRING_PROFILES_DEFAULT
).
In Spring Boot, you can also set the default profile name in application.properties
, as shown in the following example:
-
Properties
-
YAML
spring.profiles.default=dev
spring:
profiles:
default: "dev"
See Profiles in the “Spring Boot Features” section for more information.
Change Configuration Depending on the Environment
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.
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:
-
Properties
-
YAML
server.port=9000
#---
spring.config.activate.on-profile=development
server.port=9001
#---
spring.config.activate.on-profile=production
server.port=0
server:
port: 9000
---
spring:
config:
activate:
on-profile: "development"
server:
port: 9001
---
spring:
config:
activate:
on-profile: "production"
server:
port: 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 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.
A running application with the Actuator features has a configprops
endpoint that shows all the bound and bindable properties available through @ConfigurationProperties
.
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.