Search code examples
javaspringpropertiesclasspathspring-el

Spring PropertyPlaceHolder Java Config external properties file


So this has to be some silly mistake, which I've not been able to pass through. I'm trying to externalize my properties file, currently placed in my user home. I'm loading the properties file using @PropertySource like this:

@Configuration
@PropertySources(value = { @PropertySource("file:#{systemProperties['user.home']}/.invoice/config.properties") })
public class PropertiesConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertiesPlaceHolderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

But unfortunately, that is not loading the properties file. Throws FileNotFoundException. But if I change the path to:

@PropertySources(value = { @PropertySource("file:/home/rohit/.invoice/config.properties") })

it works properly. And that is the path which the earlier path resolves to. I've logged it to verify. So it seems to me that SpEL is not getting evaluated in the @PropertySource annotation. Is it supposed to work that way?

If yes, then is there any other way to read the external properties file, which sits in /home/rohit? I don't want to give absolute path, for obvious reasons. And I would like to avoid extending PropertyPlaceHolderConfigurer class.

One other option I tried was adding the /home/rohit/.invoice folder to tomcat classpath. But seems like Spring doesn't use System Classpath to resolve classpath: suffix. Any pointers on this?


Solution

  • In a @PropertySoure annotation EL expressions won't work. You are allowed to use placeholders ${...} however that is also limited to system or environment variables. However as you want to resolve the home directory of the user you can use the ${user.home} placeholder.

    @PropertySource("file:${user.home}/.invoice/config.properties")
    

    This should work as desired.