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

Spring应用启动报错:BeanCreationException与PropertyReferenceException求助

排查Spring Data JPA自定义Repository方法报错:No property ... found for type ...

先看你贴的错误栈,核心问题一目了然:

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property findResultByCodeAndProfile found for type Test!

这个错误的本质是Spring Data JPA把你自定义的方法当成了基于实体属性的派生查询来解析,但你的Test实体里根本没有findResultByCodeAndProfile这个属性——这显然是框架的误解,根源在于你的自定义Repository实现不符合Spring Data JPA的约定。

具体原因分析

Spring Data JPA识别自定义Repository方法的关键是命名和位置约定:

  1. 自定义接口的命名应该和主Repository接口前缀保持一致(比如主接口是TestRepository,自定义接口一般叫TestRepositoryCustom)
  2. 自定义接口的实现类必须遵循「主Repository接口名+Impl」的命名规则(比如TestRepositoryImpl),这样框架才能找到对应的实现,而不是把自定义方法当成派生查询处理。

看你的代码,明显存在拼写不一致的问题:

  • 主Repository接口是TestRepository(正确拼写Repository)
  • 自定义接口却是TestRespositoryCustom(少了一个字母o,写成了Respository)
  • 实现类是TestRespositoryImpl(同样少了字母o)

这种命名不匹配会让Spring Data JPA找不到你的自定义实现,进而尝试把findResultByCodeAndProfile当成派生查询方法去解析,自然就会报错说Test实体没有这个属性。

解决方案

1. 修正命名,严格遵循约定

这是最关键的一步,直接解决核心问题:

  • 把自定义接口TestRespositoryCustom重命名为TestRepositoryCustom(补充缺失的字母o)
  • 把实现类TestRespositoryImpl重命名为TestRepositoryImpl(同样补充字母o)
  • 确保实现类和主TestRepository接口在同一个包下(如果不在同一个包,需要在@EnableJpaRepositories注解里通过basePackages和repositoryImplementationPostfix指定位置和后缀)

修正后的代码示例:

// 自定义接口
public interface TestRepositoryCustom {
    List<TestDto> findResultByCodeAndProfile(String testObjKey, String testObjValue);
}

// 实现类
public class TestRepositoryImpl extends BaseRepositoryCustom implements TestRepositoryCustom {
    @Override
    public List<TestDto> findResultByCodeAndProfile(String testObjKey, String testObjValue) {
        String sql = TC_NOTE_QRY;
        // 如果是原生SQL,需要用createNativeQuery并指定结果类型
        Query query = entityManager.createQuery(sql);
        query.setMaxResults(3);
        query.setParameter("testObjKey", testObjKey);
        query.setParameter("testObjValue", testObjValue);
        return query.getResultList();
    }
}

2. 额外检查项(避免后续踩坑)

  • 确认你的TC_NOTE_QRY是合法的JPQL语句:如果是原生SQL,需要用entityManager.createNativeQuery(sql, TestDto.class),否则返回的是Object数组,强转List<TestDto>会抛出类型转换异常。
  • 确认BaseRepository上的@NoRepositoryBean注解存在:这个注解会告诉Spring Data JPA不要为这个基础接口创建实例,只作为父接口被继承,你的代码里已经加了,这部分是正确的。
  • 确认EntityManager注入正常:你的BaseRepositoryCustom里用@PersistenceContext注入EntityManager是正确的,不需要修改。

总结

这个错误几乎都是因为自定义Repository的命名不符合Spring Data JPA的约定导致的,修正命名后,框架就能正确识别你的自定义实现方法,而不会去尝试解析成派生查询,问题就能解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:53:39