Spring Boot多环境配置中application-de.properties的username属性未生效问题
问题:application-de.properties中username属性无法正常注入?
配置与代码情况
- application.properties:
spring.profiles.active=de username=postgres password=12345 dburl=localhost:postgre
- application-de.properties:
username=**** postgres password=****12345 dburl=localhost:****de
- @Configuration类:
@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; }
- 主类:
@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()); }
运行现象
原配置运行输出:
User ****12345 localhost:****de
可见password和dburl加载正常,但username未读取到application-de.properties中的值。
修改application-de.properties为:
name=**** postgres password=****12345 dburl=localhost:****de
同时修改@Configuration类的注入语句:
@Value("${name}") String username;
输出恢复正常:
**** postgres ****12345 localhost:****de
原因分析
username是Spring Boot默认会读取的系统环境变量/系统属性,在Spring的属性加载优先级中,系统环境变量、系统属性的优先级高于自定义配置文件属性。当使用${username}时,Spring会优先获取当前操作系统登录用户的用户名(比如你的系统登录名是User),而非配置文件里的自定义值。
而password和dburl不属于Spring内置的系统属性/环境变量,所以Spring会按照配置文件优先级规则(激活的de profile配置文件覆盖默认application.properties配置)读取自定义值,因此能正常加载。
换成name作为属性名后,不存在与系统内置变量的冲突,Spring就会正确读取application-de.properties中配置的内容。
内容的提问来源于stack exchange,提问作者Vats
相关产品推荐
相关产品推荐

