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

Application.java中@Value注解无法读取.yml配置问题求助

问题原因

你在main方法中直接打印enabled属性时,Spring容器还未初始化完成,@Value注解的注入逻辑还没执行:

  • main是程序的静态入口,执行log.info(enabled)时,Spring还未创建Application类的Bean实例,自然不会处理@Value的注入
  • 布尔类型的默认值是false,包装类型Boolean的默认值是null,所以你看到的是这些默认值
  • Controller能正确获取是因为Controller是Spring管理的Bean,容器初始化完成后才会被实例化并完成属性注入
解决方案

推荐以下两种可靠的方式在Spring容器就绪后获取配置属性:

方式一:实现CommandLineRunner接口

CommandLineRunner的run方法会在Spring容器启动完成后自动执行,此时属性已经完成注入:

@SpringBootApplication
@Slf4j
public class Application implements CommandLineRunner {

    @Value("${backend.enabled}")
    private boolean enabled;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("backend.enabled value: {}", enabled);
    }
}

方式二:监听ApplicationReadyEvent事件

ApplicationReadyEvent是Spring容器完全启动、所有Bean初始化完成后触发的事件,比ContextRefreshedEvent更适合这个场景(后者可能因子容器存在触发多次):

@SpringBootApplication
@Slf4j
public class Application {

    @Value("${backend.enabled}")
    private boolean enabled;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        log.info("backend.enabled value: {}", enabled);
    }
}

注意:不要在main方法中直接访问@Value注入的属性,必须等待Spring容器初始化完成后再操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 00:20:03