1. 程式人生 > >Spring boot-(3) Spring Boot特性2

Spring boot-(3) Spring Boot特性2

覆蓋 -s json tde div mva ann opened 運行時

1. 外部配置

Spring Boot支持外部配置,以便可以在不同的環境中使用相同的應用程序代碼。可以使用properties文件,YAML文件,環境變量或命令行參數進行外部配置。可以使用@Value註解將屬性值直接註入到定義的bean中,可通過Spring的Environment抽象訪問該屬性,或者通過@ConfigurationProperties綁定到結構化對象。

Spring Boot使用一個特別的PropertySource順序,旨在允許合理地覆蓋值。屬性按以下順序選擇:

1) 在HOME目錄設置的Devtools全局屬性,如當devtools設置可用時,該目錄為~/.spring-boot-devtools.properties;

2) 單元測試中的@TestPropertySource註解

3) 單元測試中的@SpringBootTest#properties註解屬性

4) 命令行參數

5) SPRING_APPLICATION_JSON中的屬性(在環境變量或系統屬性中內嵌的JSON)

6) ServletConfig初始化參數

7) ServletContext初始化參數

8) java:comp/env中的JNDI屬性

9) Java系統屬性,即System.getProperties()

10) 操作系統環境變量

11) RandomValuePropertySource, 僅在random.*中有屬性

12) jar包外的Profile-specific應用屬性,如application-(profile).properties和YAML變體

13) jar包內的Profile-specific應用屬性,如application.properties和YAML變體

14) jar包外的應用屬性,如application.properties和YAML變體

15) jar包內的應用屬性,如application.properties和YAML變體

16) 在@Configuration類中的@PropertySource註解

17) 默認屬性(通過SpringApplication.setDefaultProperties指定)

例:假設開發@Component並使用一個name屬性:

技術分享圖片
import org.springframework.beans.factory.annotation.Value;
import
org.springframework.stereotype.Component; @Component public class MyBean { @Value("${name}") private String name; }
View Code

在應用的classpath(例如,在jar包)中,application.properties文件提供一個默認屬性值name。當在一個新的環境中運行時,application.properties文件可以在jar包外提供,進而替代jar包中的name。為了一次性測試,可以以指定命令行運行,如java –jar app.jar --name="Spring"

Spring boot-(3) Spring Boot特性2