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

Spring Boot获取application.properties值:跨类调用取值失败求助

问题原因及解决方案

问题核心

你在/message2接口里手动new MainConfigFiles()创建的对象,不在Spring容器的管理范围内,Spring不会对这个对象的@Value注解做属性注入操作,所以message2始终为null。而你通过@Autowired注入的mainConfigFiles是Spring管理的Bean,它的属性已经被正常注入。

修复代码

修改MessageRestController中的getMessage2方法,直接使用已注入的mainConfigFiles对象:

@RequestMapping("/message2") 
String getMessage2() { 
    String msg = mainConfigFiles.getMessage2();
    System.out.println("Msg is....."+msg);
    return msg; 
}

额外说明

  • Spring Boot项目默认会自动加载application.properties配置文件,因此MainConfigFiles上的@PropertySource(value = "application.properties")可以省略,不影响功能。
  • 所有需要Spring处理注解(如@Value、@Autowired)的类,必须由Spring容器创建和管理,不能手动通过new实例化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:35:23