综述
可以通过使用properties文件,yaml文件,环境变量以及命令行参数,来传递参数。属性值可以通过 @ConfigurationProperties 或者Spring 的
Environment抽象获得,并使用
@Value注解直接映射到bean的属性中。
SpringBoot 使用属性覆盖顺序:
- Devtools global settings properties on your home directory (
~/.spring-boot-devtools.properties
when devtools is active). @TestPropertySource
annotations on your tests.@SpringBootTest#properties
annotation attribute on your tests.- Command line arguments.
- Properties from
SPRING_APPLICATION_JSON
(inline JSON embedded in an environment variable or system property) ServletConfig
init parameters.ServletContext
init parameters.- JNDI attributes from
java:comp/env
. - Java System properties (
System.getProperties()
). - OS environment variables.
- A
RandomValuePropertySource
that only has properties inrandom.*
. - Profile-specific application properties outside of your packaged jar (
application-{profile}.properties
and YAML variants) - Profile-specific application properties packaged inside your jar (
application-{profile}.properties
and YAML variants) - Application properties outside of your packaged jar (
application.properties
and YAML variants). - Application properties packaged inside your jar (
application.properties
and YAML variants). @PropertySource
annotations on your@Configuration
classes.- Default properties (specified using
SpringApplication.setDefaultProperties
).
这里给出了一个特别注释: SPRING_APPLICATION_JSON的配置方法。
- 类Linux的shell方式:
$ SPRING_APPLICATION_JSON='{"foo":{"bar":"spam"}}' java -jar myapp.jar - 系统变量:
$ java -Dspring.application.json='{"foo":"bar"}' -jar myapp.jar - 命令行变量:
$ java -jar myapp.jar --spring.application.json='{"foo":"bar"}' - JNDI变量:
java:comp/env/spring.application.json
配置随机变量
RandomValuePropertySource可以随机生成
integers, longs, uuids or strings
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
命令行配置
默认情况下, SpringApplication会将命令行配置(以--开头,比如
--server.port=9000
)添加到Spring的环境中。
可以通过 SpringApplication.setAddCommandLineProperties(false)关闭此功能。
Application配置文件
Spring会自动加载 application.properties配置文件。扫描的路径包括:
- 当前路径下的
/config文件夹下
- 当前路径下
- classpath的/config文件夹下
- classpath的根目录
yaml文件也是同理。
如果不喜欢默认的application.properties,也可以通过配置实现其他的设定:
- 自定义
spring.config.name:
$ java -jar myproject.jar --spring.config.name=myproject - 自定义 spring.config.location
$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
默认的配置文件搜索路径: classpath:,classpath:/config,file:,file:config/(
file:config/
的优先级最高)
Profile-specific properties
可以通过制定名称来实现配置文件覆盖。 application-{profile}.properties。其中
profile通过
spring.profiles.active指定。
Placeholders in properties
application.properties中的变量可以在之后的配置中使用。
例如:
app.name=MyApp
app.description=${app.name} is a Spring Boot application
Using YAML instead of Properties
yaml为一种json格式,可以和properties相互转换。这里不涉及,所以不翻译了。
Type-safe Configuration Properties
@Value("${property}")有的时候使用起来很笨重,尤其是有多个属性,或者属性有层次关系。spring提供了一种额外的方式支持多层次,多属性情形。
两种实现方式:
-
EnableConfigurationProperties中指定配置的class
首先注册配置文件的class:
@Configuration
@EnableConfigurationProperties(FooProperties.class)
public class MyConfiguration {
}
然后通过ConfigurationProperties注解配置文件。本实例包含以下集中属性:
foo.enabled
,false
by defaultfoo.remote-address
, with a type that can be coerced fromString
foo.security.username
, with a nested "security" whose name is determined by the name of the property. In particular the return type is not used at all there and could have beenSecurityProperties
foo.security.password
foo.security.roles
, with a collection ofString
package com.example;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("foo")
public class FooProperties {
private boolean enabled;
private InetAddress remoteAddress;
private final Security security = new Security();
public boolean isEnabled() { ... }
public void setEnabled(boolean enabled) { ... }
public InetAddress getRemoteAddress() { ... }
public void setRemoteAddress(InetAddress remoteAddress) { ... }
public Security getSecurity() { ... }
public static class Security {
private String username;
private String password;
private List<String> roles = new ArrayList<>(Collections.singleton("USER"));
public String getUsername() { ... }
public void setUsername(String username) { ... }
public String getPassword() { ... }
public void setPassword(String password) { ... }
public List<String> getRoles() { ... }
public void setRoles(List<String> roles) { ... }
}
}
- ConfigurationProperties和Component配置,定义一个bean
@Component
@ConfigurationProperties(prefix="foo")
public class FooProperties {
// ... see above
}
通过以上两种方式定义的bean,可以和普通bean一样使用。
配置bean的属性,和配置文件中属性名称,有一种松散的绑定方式。
@ConfigurationProperties(prefix="person")public class OwnerProperties {
private String firstName;
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
其中firstName可以有以下集中定义方式:
person.firstName
Standard camel case syntax.
person.first-name
Dashed notation, recommended for use in .properties and .yml files.
person.first_name
Underscore notation, alternative format for use in .properties and .yml files.
PERSON_FIRST_NAME
Upper case format. Recommended when using a system environment variables.
@ConfigurationProperties的属性可以使用spring的 @Validated进行值的合法验证,也可以使用
JSR-303 javax.validation进行合法性验证。
@ConfigurationProperties vs. @Value
Feature | @ConfigurationProperties | @Value |
---|---|---|
Yes | No | |
Yes | No | |
| No | Yes |