Lily
Lily

Reputation: 375

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?

Upvotes: 1

Views: 2108

Answers (2)

alltej
alltej

Reputation: 7285

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 {

...}

Upvotes: 2

Related Questions