Optional @PropertySource location

Gerhard Schlager picture Gerhard Schlager · Jul 1, 2013 · Viewed 14.4k times · Source

I'm using Spring 3.2 in a web application and I'd like to have a .properties file within the classpath which contains default values. The user should be able to use JNDI to define a location where another .properties is stored which overrides the default values.

The following works as long as the user has set the configLocation as JNDI property.

@Configuration
@PropertySource({ "classpath:default.properties", "file:${java:comp/env/configLocation}/override.properties" })
public class AppConfig
{
}

However, the external overrides should be optional and so should the JNDI property.

Currently I get an exception (java.io.FileNotFoundException: comp\env\configLocation\app.properties (The system cannot find the path specified) when the JNDI property is missing.

How can I define optional .properties that are used only when the JNDI property (configLocation) is set? Is this even possible with @PropertySource or is there another solution?

Answer

matsev picture matsev · Jan 10, 2014

As of Spring 4, issue SPR-8371 has been solved. Consequently, the @PropertySource annotation has a new attribute called ignoreResourceNotFound that has been added for exactly this purpose. Additionally, there is also the new @PropertySources annotation which allows implementations like:

@PropertySources({
    @PropertySource("classpath:default.properties"),
    @PropertySource(value = "file:/path_to_file/optional_override.properties", ignoreResourceNotFound = true)
})