【问题标题】:Null pointer Error when accessing JPARepository method in Spring data jpa [duplicate]在Spring数据jpa中访问JPARepository方法时出现空指针错误[重复]
【发布时间】:2021-05-24 10:27:18
【问题描述】:

当我在测试中运行它时,NullPointerException 发生在以下行: Account 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();
}

【问题讨论】:

    标签: java spring-data-jpa spring-test spring-repositories


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-22
        • 2018-07-20
        • 2021-08-31
        • 2020-10-17
        • 2016-01-16
        • 2012-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多