简体   繁体   中英

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

In many documents, the usage is @PropertySource is usually like:

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

In my Spring-boot project, I have the following in application.properties

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

and in java source:

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

    public String getIndex() {
       return index;
    }

}

But I get the following exception:

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

it seems to me that @PropertySource import resource files in classpath by default, so my question is how to use @PropertySource to import resource files which are not in classpath?

You can cascade the PropertySources to provide fallback/default value.

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

...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM