This is my application.properties file
spring.profiles.active=de
username=postgres
password=12345
dburl=localhost:postgre
This is application-de.properties file
username=**** postgres
password=****12345
dburl=localhost:****de
This is @Configuration class
@Value("${username}")
String username;
@Value("${password}")
String password;
@Value("${dburl}")
String dburl;
@Bean
public static PropertySourcesPlaceholderConfigurer property(){
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new
PropertySourcesPlaceholderConfigurer();
return propertySourcesPlaceholderConfigurer;
}
@Bean
FakeDataSource fakeDataSource(){
FakeDataSource fakeDataSource = new FakeDataSource();
fakeDataSource.setUsername(username);
fakeDataSource.setPassword(password);
fakeDataSource.setDburl(dburl);
return fakeDataSource;
}
This is main class
@SpringBootApplication
public class Spring5DiDemoDiAssignmentApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Spring5DiDemoDiAssignmentApplication.class,
args);
FakeDataSource fakeDataSource = (FakeDataSource) ctx.getBean(FakeDataSource.class);
System.out.println(fakeDataSource.getUsername()+" "+fakeDataSource.getPassword()+"
"+fakeDataSource.getDburl());
This is output
User ****12345 localhost:****de
All properties set but username doesn't set. If I change apllication-de.properties as below
name=**** postgres
password=****12345
dburl=localhost:****de
and @Configuration class
@Value("${name}")
String username;
The output
**** postgres ****12345 localhost:****de
The username
property is already defined by default in your environmentProperties
and is being resolved by the PropertySourcesPropertyResolver
, so that's why you are not able to inject the value that you need.
In order to avoid such issues, the common practice is to add the prefix to your custom properties.
So, your application.properties
and application-de.properties
should contain something like
app.username=**** postgres
app.password=****12345
app.dburl=localhost:****de
and then your @Configuration
file should look contain:
@Value("${app.username}")
String username;
@Value("${app.password}")
String password;
@Value("${app.dburl}")
String dburl;
This way you should avoid collisions with any default properties.
Be aware that app
prefix is only an example and you can replace it with whatever name you wish, you can also chain prefixes like my.app.prop.username
if you wish.