Reputation: 295
I am trying to initialize two different spring beans (bean1 and bean2) with their dedicated properties files ('bean1' from 'bean1.properties', and 'bean2' from bean2.properties), with both bean1 and 2 properties file having same "enter code here'eys" with a different value. But by attempting to do so, both bean1 and bean2 are getting initialize by only "values" from bean1.properties (while bean2.properties is ignored).
The demo code is on GitHub
Basically used @PropertySource to load corresponding property file from classpath.
@Component
@PropertySource("classpath:bean1.properties")
@ConfigurationProperties
public class Bean1 {
private String symbol;
private String tenor;
// omitting code
}
@Component
@PropertySource("classpath:bean2.properties")
@ConfigurationProperties
public class Bean2 {
private String symbol;
private String tenor;
// omitting other code
}
bean1.properties:
symbol=bean1symbol
tenor=bean1tenor
bean2.properties
symbol=bean2symbol
tenor=bean2tenor
I expect the bean1 and bean2 properties initialized based on corresponding values of their properties files, [when they same same key].
When I print symbol and tenor for Bean1 and Bean2, symbol and tenor are printing same values (from bean2.properties).
Upvotes: 2
Views: 204
Reputation: 3819
Spring will read all properties files into the same namespace - so for the case that bean2.properties will be read after bean1.properties it will overwrite the already defined properties.
So maybe you could modify your properties to be named like this:
bean1.symbol=bean1symbol
bean2.tenor=bean1tenor
bean2.symbol=bean2symbol
bean2.tenor=bean2tenor
or simpler:
symbol1=bean1symbol
tenor2=bean1tenor
symbol2=bean2symbol
tenor2=bean2tenor
So please be carefully that your properties name a globally unique.
For already existing properties please have a look at Common application properties
Upvotes: 1
Reputation: 1559
The problem is with property name collision in the Spring Environment
. You are using @PropertySource
to tell Spring to source properties from additional location(s), but those properties are going into the same Environment
.
Instead, try prefixing your properties within the *.properties files and using the @ConfigurationProperties(prefix = "my.prefix")
to disambiguate properties with the same name.
For example:
@Component
@PropertySource("classpath:bean1.properties")
@ConfigurationProperties(prefix = "bean1")
@Configuration
public class Bean1 {
private String symbol;
private String tenor;
//omitting code
}
@Component
@PropertySource("classpath:bean2.properties")
@ConfigurationProperties(prefix = "bean2")
@Configuration
public class Bean2 {
private String symbol;
private String tenor;
//omitting other code
}
Then in your *.properties files you would have:
bean1.symbol=
bean1.tenor=
bean2.symbol=
bean2.tenor=
Upvotes: 1