Spring Environment读取properties异常:username返回电脑名称求助
问题描述
我在SpringConfig类中注入了Environment实例,代码如下:
private final Environment environment; @Autowired public SpringConfig(ApplicationContext applicationContext, Environment environment) { this.applicationContext = applicationContext; this.environment = environment; }
同时存在database.properties配置文件,内容为:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/first_db username=root password=1234
我创建了DataSource Bean的代码如下:
@Bean public DataSource dataSource(){ DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(Objects.requireNonNull(environment.getProperty("driver"))); dataSource.setUrl(environment.getProperty("url")); dataSource.setUsername(environment.getProperty("username")); dataSource.setPassword(environment.getProperty("password")); return dataSource; }
运行时出现错误,排查发现environment.getProperty()的返回结果为:
com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/first_db PC // 我的计算机名称 1234
请问为何Environment返回的是我的计算机名称而非配置的root?如何查看已分配的属性?
问题原因与解决方法
原因分析
Spring的Environment加载属性时存在优先级顺序,系统环境变量、JVM系统属性的优先级高于自定义的.properties配置文件。你的系统环境变量中恰好存在名为username的变量,值就是你的计算机名称,所以environment.getProperty("username")会优先读取系统变量的值,而非你配置文件里的root。
解决办法
- 修改配置键名:把
database.properties中的username改为db.username,代码中对应调整为environment.getProperty("db.username"),避免和系统变量重名。 - 调整属性源优先级:通过
@PropertySource注解的order属性,让自定义配置文件优先级高于系统环境变量。示例:
@PropertySource(value = "classpath:database.properties", order = 0)
(order数值越小优先级越高,系统环境变量默认优先级较高,设置自定义配置的order为更小值即可覆盖)
查看所有已加载属性
可以通过遍历Environment的属性源,打印所有已分配的属性,方便排查优先级冲突:
@Autowired private Environment env; public void printAllProperties() { if (env instanceof ConfigurableEnvironment) { ConfigurableEnvironment configurableEnv = (ConfigurableEnvironment) env; for (PropertySource<?> propertySource : configurableEnv.getPropertySources()) { System.out.println("=== 属性源:" + propertySource.getName() + " ==="); if (propertySource instanceof MapPropertySource) { ((MapPropertySource) propertySource).getSource().forEach((key, value) -> System.out.println(key + " = " + value) ); } } } }
调用该方法后,就能看到所有加载的属性,包括系统环境变量、JVM属性和自定义配置的内容,清晰看到各个属性的来源和值。
内容的提问来源于stack exchange,提问作者Ohonovskiy
相关产品推荐
相关产品推荐

