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

SpringBoot中@Value注解注入值为null的原因排查求助

问题原因分析

核心原因:Spring Bean初始化顺序限制

Spring创建Bean的流程是固定的:

  1. 调用构造方法实例化Bean对象
  2. 处理依赖注入(包括@Value注解的属性赋值)
  3. 执行后续初始化逻辑(如@PostConstruct标注的方法)

你的代码在构造方法里直接打印username,此时Spring还未完成@Value的属性注入操作,所以输出结果为null。

验证与解决方法

验证方式

添加@PostConstruct注解的初始化方法,在其中打印username,就能看到正确的配置值:

package com.example.SpringBootDB_H2.model;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class TestCompnent {
    @Value("${collateral.username}")
    private String username;

    public TestCompnent(){
      log.info("构造方法中 Username : {}",username);
    }

    public TestCompnent(String username){
        this.username = username;
    }

    @PostConstruct
    public void init() {
        log.info("PostConstruct中 Username : {}",username);
    }
}

启动后日志会输出:

构造方法中 Username : null
PostConstruct中 Username : ABCD

可选解决思路

  • 若需在Bean初始化阶段使用注入属性,优先使用@PostConstruct方法替代构造方法
  • 也可采用构造方法注入的方式,让属性在Bean实例化时就完成赋值:
@Component
@Slf4j
public class TestCompnent {
    private String username;

    // Spring会直接将配置值传入构造方法
    public TestCompnent(@Value("${collateral.username}") String username){
        this.username = username;
        log.info("构造方法中 Username : {}",username);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:25:11