访问Spring数据jpa中的JPARepository方法时出现空指针错误

问题描述

当我在测试中运行时,NullPointerException 出现在以下行中: 账户acc = accRepo.findAccountById(Long id); 好像 findAccountById(Long id) 返回 null。但是当我直接在任何其他测试方法调用这个方法时,它工作正常。

我的存储库文件

public Interface AccountRepo extends JpaRepository<Account,Long>{
    
    @Query("select a from Account a where a.id  = ?1")
    public List<Account> findAccountById(Long id);

}

服务接口和实现

public Interface AccountService{
    Account showAcc();
}

@Service
public class AccServiceImpl implements AccountService {
    
    @Autowired
    private AccountRepo accRepo;

    @Override
    Account showAcc(){
        Long id = 10L;
        Account acc = accRepo.findAccountById(id); // Null Pointer exception at this line
        String name = acc.getName();
        System.out.println(name);
    }

}

@Autowired
AccountServiceimpl accServImpl;

@Test
public void testAccount(){
    
    accServImpl.showAcc();
}

解决方法

您需要在测试中为您的 AccServiceImpl 提供 AccountRepo。 @Autowired 注释仅在您有应用程序上下文时才有效,而在您的测试中则不然。

因此您需要在 AccServiceImpl 中添加一个 setter 或构造函数来提供 AccountRepo。

如果要使用应用程序上下文进行测试,则需要实现 @SpringBootTest

,

您有空指针异常,因为如果您在测试框架的上下文之外运行时获得 NPE,则 AccountRepo 不会在您的测试用例或实际设置中自动装配。您需要检查您的测试配置并确保 accountrepo 实例是由您的测试框架创建和注入的。