大部分的設定訊息,我們都是配置在application.properties,那麼這個檔案是否可以外置吶?這個當然是可以的。
首先在application.preperties定義一個屬性:
demo.name = hello.01
在Controller進行使用:
@Value("${demo.name}")
private String demoName;
@RequestMapping("/test")
public String test(){
return this.demoName;
}將專案打成jar包,使用java -jar的方式進行啟動:
java -jar springboot-out-properties-0.0.1-SNAPSHOT.jar
此時讀取的值是:hello.01。
將專案中的application.properties拷貝出來,放到和jar包同路徑下,修改屬性值為:
demo.name = hello.02
然後使用上面的命令重新啟動,看下效果讀取的值就是hello.02了,驚不驚喜意不意外,Spring Boot太牛了,jar包同路徑下就直接讀取了。
如果我們在jar下新建一個config,然後把application.properties放進去的話,使用上面的指令可以辨識嗎 ?答案是可以的,
SpringApplication 將從 application.properties 以下位置的檔案中載入屬性並且將其新增至Spring 的環境當中:
#目前目錄下的/config 子目錄
classpath根目錄
#classpath中的/config 目錄
目前目錄
如果自訂的目錄,例如conf的話,這個時候就不能辨識了,但可以使用--spring.config.location進行指定路徑,執行指令如下:
java -jar springboot-out-properties-0.0.1-SNAPSHOT.jar--spring.config.location=conf/application.properties
當然也可以使用絕對路徑來指定:
java -jar springboot-out-properties-0.0.1-SNAPSHOT.jar--spring.config.location=/Users/linxiangxian/Downloads/conf/application.properties
在專案中,有些設定會自訂propreties檔案進行使用,例如定義了demo.properties:
demo.nickname = hello.10 demo.weixin = springboot
使用@PropertySource指定設定檔:
/**
* @PropertySource的例子
* <p>
*/
@Configuration
@ConfigurationProperties(prefix = "demo")
@PropertySource(value = {"classpath:demo.properties"})
public class DemoProperties {
private String nickname;
private String weixin;
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getWeixin() {
return weixin;
}
public void setWeixin(String weixin) {
this.weixin = weixin;
}
@Override
public String toString() {
return "DemoProperties{" +
"nickname='" + nickname + '\'' +
", weixin='" + weixin + '\'' +
'}';
}
}那麼此時是可以存取到這個設定檔的,打成jar包,執行指令:
java -jar springboot-out-properties-0.0.1-SNAPSHOT.jar
#此時傳回的值是:hello.10
將demo.properties放到和jar包同路徑下,修改demo.name的值為hello.11,執行上面的指令,芭比Q了,結果還是hello .10,說明Spring Boot對於自訂的properties檔案並不能自己從外部去尋找。
那對於這個問題咱麼破呢?
很簡單,@PropertySource支援多配置多個路徑,可以這麼配置:
@PropertySource(value = {"classpath:demo.properties","file:./demo.properties"},ignoreResourceNotFound = true)當我們配置多路徑,且多路徑下設定檔都存在時,SpringBoot會都載入且會覆蓋相同內容。所以當我們設定資訊只區分外部和內部路徑、內容完全相同時,將file路徑寫在後面就可以了。當我們本地啟動時,因為不存在file路徑,所以會載入classpath;當jar啟動時,file路徑會覆寫classpath路徑下的內容;
ignoreResourceNotFound = true 一定要加上,否則找不到會報錯。加上之後會忽略找不到的設定檔。
此時將設定檔demo.properties放到和jar包同級下就可以了。
以上是SpringBoot專案打成jar後怎麼載入外部設定文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!