SpringBoot版本:1.5.13.RELEASE
對應官方文檔鏈接:https://docs.spring.io/spring-boot/docs/1.5.13.RELEASE/reference/htmlsingle/
CSDN鏈接:https://blog.csdn.net/zhichao_qzc/article/details/80698755
上一篇:SpringBoot 入門篇(三) SpringApplication
??SpringBoot外部配置屬性值的方式有很多種,SpringBoot為這多種配置方式指定了優先級,在屬性相同的情況下,優先級高的配置方式會覆蓋優先級低的配置方式。當然,如果屬性不相同,則這些配置方式中的屬性值都會被加載。
??SpringBoot官方文檔指明了這多種配置方式的優先級,按照從高到低排序如下:
??(1)如果使用了Devtools,則優先級最高的是在home目錄下指定的Devtools全局配置文件~/.spring-boot-devtools.properties(優先級最高)。
??(2)測試用例中,標注了 @TestPropertySource 配置項;
??(3)測試用例中,@SpringBootTest 注解中的 properties 屬性值;
??(4)命令行參數;
??(5)內嵌在環境變量或者系統變量中的SPRING_APPLICATION_JSON中的屬性值;
??(6)ServletConfig 初始化的參數;
??(7)ServletContext 初始化的參數;
??(8)java:comp/env 中的JNDI屬性值;
??(9)Java的系統變量,通過System.getProperties()方法獲取;
??(10)操作系統的環境變量;
??(11)RandomValuePropertySource配置的${random.}屬性值;
??(12)不在項目打成可執行jar包中的application-{profile}.properties或者application-{profile}.yml文件;
??(13)項目打成可執行jar包中的application-{profile}.properties或者application-{profile}.yml文件;;
??(14)不在項目打成可執行jar包中的application.properties或者application.yml文件;*
??(15)項目打成可執行jar包中的application.properties或者application.yml文件;
??(16)同時標注@Configuration和@PropertySource的類中,標注了@PropertySource指定的屬性值;
??(17)在main方法中設置的SpringApplication.setDefaultProperties值(優先級最低)。
??在下面的例子中,包含第(4)、(14)、(15)、(16)、(17)條中的屬性設置方式,這5種方式也是開發過程中用得最多的方式。需要說明的是,MyConfiguration 類中,使用@Value("${name}")來獲取外部配置的值。
@SpringBootApplication
@RestController
public class Application {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(Application.class);
Map<String,Object> proMap = new HashMap<String, Object>();
proMap.put("name","(17)在main方法中設置的SpringApplication.setDefaultProperties值。");
application.setDefaultProperties(proMap);
application.run(args);
}
@Autowired
private MyConfiguration myConfiguration;
@RequestMapping("/getName")
public String getName(){
return myConfiguration.getName();
}
}
/**
* Create by qiezhichao on 2018/6/14 0014 21:59
*/
@Configuration
@PropertySource(value= {"classpath:propertySource.properties"})
public class MyConfiguration {
// @Value("${name}")來獲取外部配置的值
@Value("${name}")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
??代碼結構如圖
??配置命令行參數,其中--spring.config.location=X:/application.properties表示加載本地磁盤X下的 application.properties 文件。
??執行main方法,在瀏覽器輸入http://localhost:8080/getName 得到如下結果
??對于隨機值的配置,官方文檔指明可以使用${random.*}(通常在application.properties或者application.yml文件中)來注入隨機值。
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]}
??對于命令行參數,通過 java -jar app.jar --name="SpringBoot" --server.port=9090 的方式來傳遞參數。參數用 --xxx=xxx 的形式傳入。如果我們想禁用命令行參數,可以使用SpringApplication.setAddCommandLineProperties(false)的方法禁止命令行配置參數傳入。
上一篇:SpringBoot 入門篇(三) SpringApplication
下一篇:SpringBoot 入門篇(五) SpringBoot的配置文件