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

Spring @Value注解始终获取null值 求排查原因与解决方法

问题原因及解决办法

核心原因

你遇到的问题是**@Configuration类中@Bean方法的执行时机早于@Value字段的注入时机**:当Spring初始化WebConfig并调用getFromProperty()创建Person Bean时,propertyValue字段还未被@Value注解完成注入,因此传入Person构造器的是null。

另外,你的application.properties中属性值带了多余引号,虽然这不是导致null的直接原因,但会让最终读取到的属性值包含引号,建议修正。


解决办法

办法1:将@Value注入到@Bean方法参数(推荐)

直接在@Bean方法的参数上使用@Value,Spring会在调用方法时直接注入属性值,无需依赖类字段:

@Configuration
@PropertySource("classpath:/application.properties")
@ComponentScan("org.example")
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    // 移除原有的private String propertyValue字段

    @Bean
    public Person getFromProperty(@Value("${app.person.url}") String url) {
        return new Person(url);
    }
}

办法2:通过Environment获取属性

在WebConfig中注入Environment,直接从环境中读取属性值:

@Configuration
@PropertySource("classpath:/application.properties")
@ComponentScan("org.example")
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private Environment env;

    @Bean
    public Person getFromProperty() {
        String url = env.getProperty("app.person.url");
        return new Person(url);
    }
}

办法3:修正PropertySourcesPlaceholderConfigurer配置(若坚持使用类字段@Value)

在无Spring Boot的环境下,PropertySourcesPlaceholderConfigurer是处理@Value占位符的核心Bean,必须以静态方法声明,确保它在WebConfig实例化前被创建:

@Configuration
@PropertySource("classpath:/application.properties")
@ComponentScan("org.example")
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Value("${app.person.url}")
    private String propertyValue;

    // 必须是静态@Bean方法
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public Person getFromProperty() {
        return new Person(propertyValue);
    }
}

额外配置修正

修改application.properties中的属性,去掉多余的引号:

app.person.url=jdbc:h2:\\test\\h2test

内容的提问来源于stack exchange,提问作者user27486366

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 03:15:11