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

Spring Boot项目@Autowired注入Bean报NullPointerException问题求助

问题根本原因

触发空指针的核心原因有两点:

  1. LoadServiceImpl实现类没有添加Spring组件注解,没有被纳入IoC容器管理,Spring找不到可注入的LoadService类型Bean
  2. @Autowired注解设置了required=false,注入失败时不会在启动阶段抛出异常,只会给对应字段赋值为null,调用方法时才触发空指针

解决步骤

  • 给LoadServiceImpl类添加@Service注解,标注为Spring业务层组件,会被自动扫描纳入容器管理:
package com.Load.lsy.service;

import org.springframework.stereotype.Service;
import java.util.List;
import java.util.*;
import com.Load.lsy.Entities.Load;

@Service // 新增该注解
public class LoadServiceImpl implements LoadService {
    List<Load> list;

    public LoadServiceImpl() {
        list = new ArrayList<>();
    }

    @Override
    public String getLoads() {
        return "Load list" ;
    }
}
  • 调整STSController中的@Autowired配置,移除required=false,注入失败时启动阶段就会报错,提前暴露问题:
@Autowired
public LoadService service;
  • 重启项目后再次调用/home接口即可正常返回结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:36:09