Reputation: 1204
I have a couple property files, described in configuration
@Configuration
@PropertySources({
@PropertySource(name="p1", value = "classpath:p1.properties"),
@PropertySource(name="p2", value = "classpath:p2.properties")})
Both files have properties with the same keys and different values, for example:
prop1=11
prop2=12
and
prop1=21
prop2=22
How to refer to the right property source to use value? I mean smth like
@Value("${p1.prop1}")
private int prop11;
@Bean
public SomeBean someBean() {
return new SomeBean(prop11);
}
but @Value("${p1.prop1}")
is my wrong attempt.
Upvotes: 1
Views: 1731
Reputation: 417
Indeed the duplicate properties will be merged and the one last read will always be returned. But there is a way.
At first, you have to give different names to the 2 Property Sources.
@PropertySource(name="app1", value="app1.properties")
@PropertySource(name="app2", value="app2.properties")
Use ConfigurableEnvironment to retrieve all the Mutable Property Sources. And using this you can retrieve the exact Property Source with the name. This Property Source would have the exact data that was given in the associated property file.
ConfigurableEnvironment configurableEnvironment = context.getEnvironment();
MutablePropertySources propertySources = configurableEnvironment.getPropertySources();
PropertySource<?> propertySource = propertySources.get("app1");
System.out.println(propertySource.getProperty("name"));
propertySource = propertySources.get("app2");
System.out.println(propertySource.getProperty("name"));
Good luck!
Upvotes: 1
Reputation: 33789
You can't. The two property sources will be merged into the same Spring Environment. The last declared value for the same key in the your .properties files will override any previous value for the same key. If your read the JavaDoc of @PropertySource you will find the following statement:
In cases where a given property key exists in more than one .properties file, the last @PropertySource annotation processed will 'win' and override.
Upvotes: 3