SpringBoot项目services层@Value注入值始终为null如何排查解决
问题根因
@Value 注入为null和配置文件路径、注解导包没有关系,核心问题是你没有使用Spring容器管理的Service实例,而是手动通过new关键字创建了对象。
Spring的所有注解注入能力(包括@Value、@Autowired)仅对Spring IoC容器自身创建、托管的Bean生效。你虽然在MyService类上加了@Service注解,容器启动时确实会扫描创建一个对应的托管Bean,但你在Controller里完全没用到这个托管Bean,而是自己写了new MyService()生成了一个脱离容器管控的普通Java对象,这类对象不会被Spring处理任何注入逻辑,所有被@Value修饰的字段自然保持默认值null。
问题出在Controller里的这段错误代码:
@Autowired private final static MyService myService = new MyService();
这段代码同时犯了两个Spring开发的典型错误:
- Spring不支持给静态(
static)字段做依赖注入,@Autowired加在静态字段上本身就不会生效 - 手动调用构造方法实例化Service,彻底绕过了Spring的Bean生命周期管理,这个手动创建的实例不会走任何属性注入流程。
另外你在Controller类上加了Lombok的@RequiredArgsConstructor注解,又自己写静态字段手动实例化依赖,两种注入方式完全冲突。
修复方案
删掉Controller里错误的Service实例化代码,选择下面任意一种规范写法即可:
构造器注入(推荐,适配你已引入的Lombok)
package myapi.api.controllers; import java.util.List; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import myapi.api.services.MyService; import lombok.RequiredArgsConstructor; @RestController @RequestMapping("api") @RequiredArgsConstructor public class APIController { // 不要加static修饰,不要手动new赋值,声明为final即可 // Lombok会自动生成包含该字段的构造方法,Spring会自动注入容器托管的MyService实例 private final MyService myService; @GetMapping("/getdata") public List<Data> getData() { return myService.getData(); } }
字段注入(写法简单,不推荐生产环境使用)
package myapi.api.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import myapi.api.services.MyService; @RestController @RequestMapping("api") public class APIController { // 不要加static,不要手动new赋值 @Autowired private MyService myService; @GetMapping("/getdata") public List<Data> getData() { return myService.getData(); } }
修改完成后重启项目,Controller拿到的就是Spring初始化完成、已经做好所有属性注入的Service实例,@Value修饰的字段就能正常读取到配置值或者直接写入的固定字符串了。
排查提示:后续遇到Spring容器相关的注解注入为null的问题,优先排查使用的对象是否是手动new出来的,这类场景占这类问题的90%以上。
内容的提问来源于stack exchange,提问作者Andrew Estes
相关产品推荐
相关产品推荐

