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

Spring Boot中Controller注入Service为空,请求技术协助

解决Spring Boot Controller中@Autowired注入Service为null的问题

常见原因及修复方案

1. Controller方法权限错误

你的createObj方法用private修饰,Spring MVC无法代理私有方法,会导致Controller实例并非Spring容器管理的代理对象,最终注入失败。把方法权限改为public:

@PostMapping
public Object createObj(@RequestBody Object ques){
    Object save = myService.insert(ques);
    return save;
}

2. Service类未被Spring托管

你的Service接口的实现类必须添加@Service注解,让Spring识别并纳入容器管理,否则Spring找不到可注入的实例:

@Service
public class MyServiceImpl implements Service {
    // 实现insert方法逻辑
}

注意:如果Service是自定义接口,避免和Spring的org.springframework.stereotype.Service重名,建议重命名接口(比如TreeService)减少混淆。

3. Controller类未被Spring扫描到

确保controller类所在的包,在Spring Boot主启动类的扫描范围内(@SpringBootApplication默认扫描主启动类所在包及子包)。如果不在,可通过@SpringBootApplication(scanBasePackages = "你的controller所在包路径")指定扫描范围。

4. 避免手动实例化Controller

不要通过new controller()的方式创建Controller对象,必须由Spring容器负责实例化,否则注入的Service会是null。

5. 改用构造方法注入(官方推荐)

字段注入存在潜在问题,建议使用Spring官方推荐的构造方法注入,从根源避免注入null的情况:

@RestController
@RequestMapping("/api/tree")
public class Controller {

    private final Service myService;

    // Spring 4.3+ 无需添加@Autowired
    public Controller(Service myService) {
        this.myService = myService;
    }

    @PostMapping
    public Object createObj(@RequestBody Object ques){
        Object save = myService.insert(ques);
        return save;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 18:52:05