You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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。

解决办法

  1. 修改配置键名:把database.properties中的username改为db.username,代码中对应调整为environment.getProperty("db.username"),避免和系统变量重名。
  2. 调整属性源优先级:通过@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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 03:01:38