Java Spring:如何使用@PropertySource导入不在类路径中的资源文件?
在许多文档中,用法是@PropertySource,通常如下所示:Java Spring:如何使用@PropertySource导入不在类路径中的资源文件?,java,spring,spring-boot,Java,Spring,Spring Boot,在许多文档中,用法是@PropertySource,通常如下所示: @PropertySource("classpath:/document.properties") 在我的Spring boot项目中,我在application.properties config.path=/home/myservice/config.properties 在java源代码中: @PropertySource(value = {"${config.path}"}, encoding="utf-8") pu
@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(value={“file:${config.path}”,encoding=“utf-8”)
试试这个:@PropertySource(值={“文件:${config.path}”},encoding=“utf-8”)
您可以级联
属性资源
,以提供回退/默认值
@PropertySources({
@PropertySource(value = "classpath:/document.properties"),
@PropertySource(value ="file:/conf/document.properties", ignoreResourceNotFound=true)
})
public class MyConfig {
...}
您可以级联
属性资源
,以提供回退/默认值
@PropertySources({
@PropertySource(value = "classpath:/document.properties"),
@PropertySource(value ="file:/conf/document.properties", ignoreResourceNotFound=true)
})
public class MyConfig {
...}
第二个@PropertySource是默认值,而第一个是回退?如果有三个项目呢?您可以根据需要添加更多PropertySource。它们将按顺序加载。我记不起顺序,现在也无法尝试(远离PC)在我看来它似乎不符合顺序,至少对于您在回答中所写的情况,
文件:
在类路径之前:
第二个@PropertySource是默认的,而第一个是回退?如果有三个项目呢?您可以根据需要添加更多PropertySource。它们将按顺序加载。记不起顺序,我现在无法尝试(远离PC)在我看来这似乎不符合顺序,至少对于您在回答中所写的情况,文件:
在类路径之前: