Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use properties files, YAML files, environment variables, and command-line arguments to externalize configuration. Property values can be injected directly into your beans by using the
@Value
annotation, accessed through Spring’sEnvironment
abstraction, or be bound to structured objects through@ConfigurationProperties
.Spring Boot 允许我们扩展配置信息。通过属性文件、YAML文件,环境变量,命令行参数进行扩展。属性值通过 @Value 注解直接注入到 Spring Bean 中。通过 Spring Environment 这个抽象类进行访问,或者通过
@ConfigurationProperties绑定的对象进行访问。
Spring Boot uses a very particular
PropertySource
order that is designed to allow sensible overriding of values注意属性值的加载和覆盖。
PropertySource:Abstract base class representing a source of name/value property pairs。
Accessing Command Line Properties
// 调整应用的端口为9000
// 犹豫命令行的优先级高于application.properties,所以可以覆盖
java -jar xxx.jar --server.port=9000
// 禁用命令行参数
SpringApplication.setAddCommandLineProperties(false)
Application Property Files
SpringApplication loads properties from application.properties files in the following locations and adds them to the Spring Environment:
1.A /config subdirectory of the current directory
2.The current directory
3.A classpath /config package
4.The classpath root
Spring Boot 加载 application.properites 的顺序 1 > 2 > 3 > 4。
自定义配置文件的文件名和文件路径
java -jar myproject.jar --spring.config.name=myproject
java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
Profile-specific Properties
如果没有通过 spring.profiles.active 激活要加载的配置文件,Spring Boot 默认加载appilcation-default.properties
Placeholders in Properties
app.name=MyApp
app.description=${app.name} is a Spring Boot application
Type-safe Configuration Properties
第一步:绑定 key/value
通过使用 ConfigurationProperties 自动绑定 application.proeprteis 中的 key/value 到 AcmeProperties 对象中
第二步:激活
@Configuration
@EnableConfigurationProperties(AcmeProperties.class)
public class MyConfiguration {
}
第三步:
通过 @Autowired 注入 AcmeProperties 即可
注意:复杂类型的绑定也是一样的。
@ConfigurationProperties Validation
@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties {
@NotNull
private InetAddress remoteAddress;
@Valid
private final Security security = new Security();
// ... getters and setters
public static class Security {
@NotEmpty
public String username;
// ... getters and setters
}
}
@ConfigurationProperties vs. @Value