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

Spring构造函数注入后字段为null问题排查求助

问题排查:UserService在login方法中为null的原因及解决办法

核心问题出在login方法的修饰符上——你用了private来修饰这个请求处理方法。

Spring MVC处理HTTP请求时,依赖代理机制管理Controller实例:

  • Spring会为容器中的Controller创建代理对象,请求到来时通过代理对象调用对应的处理方法。
  • 如果方法是private的,Spring无法为该方法生成代理逻辑,此时实际调用的可能不是Spring容器中已完成依赖注入的Controller实例,而是直接实例化的新对象,这就导致userService未被赋值,出现null异常。

解决办法

将login方法的修饰符改为public,确保Spring能正常代理并调用容器中已完成依赖注入的Controller实例:

@RestController
@RequestMapping("/v1/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        System.err.println(userService);
        this.userService = userService;
        System.err.println(this.userService);
    }

    @PostMapping("/login")
    public ResponseEntity<ServiceResponse<UserResp>> login(@RequestBody UserReq userReq) {
        System.err.println(userService);
        return ResponseEntity.ok(userService.login(userReq));
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:20:26