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

Spring项目StudentRepository注入为空引发NullPointerException求助

解决Spring MVC中StudentRepository注入为空的问题

问题现象

提交学生信息时触发HTTP 500内部服务器错误,根源为StudentServiceImpl中的studentRepository字段为空,调用save()方法时抛出NullPointerException。

问题原因

查看StudentServiceImpl代码可知:

  • 类中同时存在无参构造函数和带参构造函数
  • 带参构造函数上的@Autowired注解被注释
  • Spring容器在创建Bean时,若存在多个构造函数,默认会选择无参构造函数实例化对象,导致studentRepository未被注入,最终为空。

解决方案

以下两种方案任选其一即可:

方案1:启用构造函数的@Autowired注解

在带参构造函数上恢复@Autowired注解,告诉Spring使用该构造函数注入StudentRepository:

@Service
public class StudentServiceImpl implements StudentService{

    private StudentRepository studentRepository;

    public StudentServiceImpl() {
        super();
    }

    @Autowired
    public StudentServiceImpl(StudentRepository studentRepository) {
        super();
        this.studentRepository = studentRepository;
        System.out.println("Student Repo:= "+this.studentRepository);
    }

    // 其他业务方法不变...
}

方案2:删除无参构造函数(推荐)

Spring 4.3及以上版本中,当类仅有一个构造函数时,会自动通过该构造函数注入依赖,无需额外添加@Autowired注解。删除无参构造函数后,Spring会自动使用带参构造函数注入StudentRepository:

@Service
public class StudentServiceImpl implements StudentService{

    private final StudentRepository studentRepository;

    public StudentServiceImpl(StudentRepository studentRepository) {
        super();
        this.studentRepository = studentRepository;
        System.out.println("Student Repo:= "+this.studentRepository);
    }

    // 其他业务方法不变...
}

验证修改

重启Spring项目后,再次提交学生信息,studentRepository会被正确注入,不会再触发空指针异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 01:31:15