簡體   English   中英

Spring:如何使用@PropertySource導入不在classpath中的資源文件?

[英]Spring: how to use @PropertySource to import resource files which are not in classpath?

在許多文檔中,@ PropertySource的用法通常是這樣的:

@PropertySource("classpath:/document.properties")

在我的Spring-boot項目中, application.properties包含以下內容

config.path=/home/myservice/config.properties

並在Java源代碼中:

@PropertySource(value = {"${config.path}"}, encoding="utf-8")
public class MyConfig {
    @Value("${myconfig.index}")
    private String index;

    public String getIndex() {
       return index;
    }

}

但是我得到以下異常:

Caused by: java.io.FileNotFoundException: class path resource [home/myservice/config.properties] cannot be opened because it does not exist

在我看來,@ PropertySource默認情況下會在類路徑中導入資源文件,所以我的問題是如何使用@PropertySource導入不在類路徑中的資源文件?

嘗試以下方法:@PropertySource(值= {“文件:$ {config.path}”},編碼=“ utf-8”)

指示要加載的屬性文件的資源位置。 例如,“ classpath:/com/myco/app.properties”或“ file:/ path / to / file”。

您可以級聯PropertySources以提供回退/默認值。

@PropertySources({
        @PropertySource(value = "classpath:/document.properties"),
        @PropertySource(value ="file:/conf/document.properties", ignoreResourceNotFound=true)
})
public class MyConfig {

...}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM