You can have properties files automatically loaded in Spring by using the PropertySourcesPlaceholderConfigurer
.
Here is an example of configuring a PropertySourcesPlaceholderConfigurer
using Spring JavaConfig:
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer props = new PropertySourcesPlaceholderConfigurer();
props.setLocations(new Resource[] {
new ClassPathResource("/config/myconfig.properties"),
new ClassPathResource("version.properties")
});
}
This will load the properties from the files above on the classpath.
You can use these properties in property replacements within your application. For example, assume that there is a property in one of those files above named myprop
. You could inject myprop
's value into a field using the following:
@Value(${myprop})
private String someProperty;
You can also access the values of the properties by injecting Spring's Environment
object into your classes.
@Resource
private Environment environment;
public void doSomething() {
String myPropValue = environment.getProperty("myprop");
}
In order to read any old file from within a web application the link that Frederic posted in the comments above provides a good explanation of the normal classloader hurdles one encounters when attempting to read files from within their war file and the solutions around it.