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

Spring Boot中Controller与JSP执行REST操作遇空指针问题求助

问题原因

错误提示this.shoeService is null,本质是Spring没有将ShoeService的实例注入到WareHouseController中。REST接口能正常工作,说明ShoeService的实现类已经被Spring容器管理,只是MVC控制器的注入方式有误。

解决方案

解决核心是让Spring完成ShoeService到控制器的依赖注入,以下是三种可行方式:

方式1:使用@Autowired注解注入

在控制器的shoeService字段上添加@Autowired注解,Spring会自动匹配并注入对应的实现类实例:

@Controller
public class WareHouseController {

    @Autowired
    private ShoeService shoeService;
    
    @RequestMapping(value="/getallitem", method=RequestMethod.GET)
    public String getAllItem() {
        List allShoes =  shoeService.findAll();
        System.out.println(allShoes);
        return "warehouse";
    }
}

方式2:构造函数注入(推荐)

这是Spring官方推荐的依赖注入方式,能保证依赖不可变,从根源避免空指针问题:

@Controller
public class WareHouseController {

    private final ShoeService shoeService;
    
    // 构造函数注入
    public WareHouseController(ShoeService shoeService) {
        this.shoeService = shoeService;
    }
    
    @RequestMapping(value="/getallitem", method=RequestMethod.GET)
    public String getAllItem() {
        List allShoes =  shoeService.findAll();
        System.out.println(allShoes);
        return "warehouse";
    }
}

方式3:确认Service实现类被Spring管理

检查ShoeService的实现类(比如ShoeServiceImpl)是否添加了@Service注解,只有加了该注解,Spring才能扫描并创建实例供注入:

@Service
public class ShoeServiceImpl implements ShoeService {
    @Override
    public List<ShoeData> findAll() {
        // 具体业务逻辑实现
    }
    // 其他接口方法的实现
}
额外检查点
  • 确保Spring的组件扫描范围包含ShoeService实现类所在的包,Spring Boot主启动类上的@SpringBootApplication默认会扫描其所在包及子包。
  • 如果使用自定义扫描路径,需通过@ComponentScan注解明确指定包含Service实现类的包。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:21:35