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

SpringBoot中JpaRepository调用findById报NullPointerException求助

Maven转SpringBoot后JpaRepository注入空指针问题

我正在将Maven项目转换为SpringBoot应用,调用JpaRepository的findById()方法前项目运行正常,但调用该方法时抛出空指针异常,提示this.rDatenherkunft为null。

Repository代码

package demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import demo.model.Datenherkunft;

@Repository
public interface RepositoryDatenherkunft extends JpaRepository<Datenherkunft, Integer>{}

调用类代码

package demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import demo.model.*;
import demo.repository.*;

@Service
public class ForeignKeyObjects implements ServiceGet{

    @Autowired
    private RepositoryDatenherkunft rDatenherkunft;

    @Override
    public Datenherkunft getDatenherkunft(Integer datenherkunft) {
        return rDatenherkunft.findById(datenherkunft).get();
    }
}

抛出的异常

java.lang.NullPointerException: Cannot invoke "demo.repository.RepositoryDatenherkunft.findById(Object)" because "this.rDatenherkunft" is null
    at demo.service.ForeignKeyObjects.getDatenherkunft(ForeignKeyObjects.java:34) ~[classes/:na]
    at demo.service.ListenInhaltValidation.listenInhaltValidation(ListenInhaltValidation.java:15) ~[classes/:na]
    at demo.service.DtoValidation.dtoValidation(DtoValidation.java:15) ~[classes/:na]
    at demo.service.ServiceImp.createobjects(ServiceImp.java:50) ~[classes/:na]
    at demo.controller.Controller.createObjects(Controller.java:29) ~[classes/:na]
    ...

我是编程和SpringBoot新手,项目结构有些混乱。这个类设为Service而非Controller,是因为它负责数据入库前的验证和转换,我认为这类逻辑属于服务层。

我尝试过以下方法,但都没有解决问题:

  • 将@Service改为@Controller
  • 在每个变量上添加@Autowired
  • 在Repository上添加@Repository注解

解决思路

空指针的核心原因是ForeignKeyObjects这个Bean没有被Spring容器正确管理,或者调用它时是手动new出来的,而非通过Spring注入获取。

  1. 检查Spring扫描范围
    确保SpringBoot启动类(带@SpringBootApplication的类)所在包是demo或包含demo.service、demo.repository子包。如果启动类在更深层级(比如demo.app),需手动指定扫描路径:

    @SpringBootApplication(scanBasePackages = "demo")
    public class YourApplication {
        public static void main(String[] args) {
            SpringApplication.run(YourApplication.class, args);
        }
    }
    

    同时确认没有通过@ComponentScan的exclude规则误排除相关类。

  2. 修正调用方式
    从异常栈的调用链来看,ForeignKeyObjects是被ListenInhaltValidation调用的,你需要确保在ListenInhaltValidation中是通过@Autowired注入ForeignKeyObjects,而非手动new对象:

    @Service
    public class ListenInhaltValidation {
        @Autowired
        private ForeignKeyObjects foreignKeyObjects;
    
        public void listenInhaltValidation(...) {
            foreignKeyObjects.getDatenherkunft(...);
        }
    }
    

    手动new的对象不会被Spring管理,自然无法注入依赖的Repository。

  3. 改用构造器注入(推荐)
    字段注入(@Autowired加在字段上)容易出现依赖未注入的问题,改用构造器注入更安全,还能强制保证依赖不为空:

    @Service
    public class ForeignKeyObjects implements ServiceGet{
    
        private final RepositoryDatenherkunft rDatenherkunft;
    
        // Spring 4.3+无需加@Autowired,会自动装配
        public ForeignKeyObjects(RepositoryDatenherkunft rDatenherkunft) {
            this.rDatenherkunft = rDatenherkunft;
        }
    
        @Override
        public Datenherkunft getDatenherkunft(Integer datenherkunft) {
            // 建议用orElse/orElseThrow替代get(),避免NoSuchElementException
            return rDatenherkunft.findById(datenherkunft).orElse(null);
        }
    }
    
  4. 检查JPA依赖配置
    确保pom.xml中已引入Spring Data JPA的starter依赖:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    

    另外,@Repository注解可以省略,Spring Data JPA会自动识别继承JpaRepository的接口并创建代理Bean。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:35:37