In this post under Spring Core, I will show with example how to configure access to multiple custom property files.
In the previous post, I showed with example how to configure access to single custom property file.
In real world scenario they wouldn’t be a situation where we need access to only one custom property file.
We always need access to multiple properties file.
For these kind of situation we take help of “@PropertySources” annotation.
Below is the snapshot
@PropertySources(
{
@PropertySource("app1.properties"),
@PropertySource("app2.properties")
}
)
Where “app1.properties” and “app2.properties” are names of two properties file present in application classpath.
The way we access a property present in these properties file is same, that is using “getProperty” method on “Environment” instance.
Below is the snippet of code showing how to access a property.
getEnvironment().getProperty("name");
Spring code searches for a particular property in the files in the order they are declared. That is it first checks “app1.properties” and then “app2.properties” file.
If there exist a situation where a property is present in two files. Precedence is given to last file read containing the property by that name.
For our example lets take below two properties file
app1.properties
name=Sam Fisher
location=United States
app2.properties
age=37
location=United Kingdom
As you can see from the code, both the properties file has “location” property common. So when we try to read the value of the property using “getEnvironment().getProperty()” method.
The value “United Kingdom” present in “app2.properties” file is printed.
As that is the properties file that is read at the last.
Below is the complete main code for your reference
Main class
package package37;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;
@Configuration
@PropertySources(
{
@PropertySource("app1.properties"),
@PropertySource("app2.properties")
}
)
public class Example37 {
@Autowired
private Environment environment;
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example37.class);
Example37 example37 = applicationContext.getBean(Example37.class);
String result = example37.getEnvironment().getProperty("name");
System.out.println(result);
result = example37.getEnvironment().getProperty("location");
System.out.println(result);
}
public Environment getEnvironment() {
return environment;
}
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}