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