SpringData JPA 报错 NoSuchBeanDefinitionException
最近学习学习使用SpringData JPA,刚开始的示例项目都没有问题。直到创建了一个SpringBoot项目,启动类和Repository以及Entity不在同一包中。结果在测试Repository接口时报错:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xxx.xxx.RepositoryTest': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'xxx.xxx.xxx' available: expected at least 1 bean which qualifies as autowire candidate.
没有自动生成接口的实现类。刚开始以为是Repository接口没有扫描到,也确实和启动类在不同的包中中,于是在启动类上添加Repository和Entity所在的包
@SpringBootApplication(scanBasePackages = {"xxx.xxx.xxx","yyy.yyy.yyy"})
结果还是报同样的错误。在包下写其他的自定义接口和实现类,SpringBoot可以扫描到。
这就奇怪了...
求助百度,原来这种错误有两种解决办法:
- 方案一:把
@SpringBootApplication
注解的SpringBoo启动类移到上层root包中,使JpaRepository子接口位于root包及其子包中。所以之前的示例项目没有问题,因为启动类是自动生成的,在包的最外层。
- 方案二:添加
@EnableJpaRepositories(basePackages = "xxx.xxx.xxx")用以扫描@Repository
注解
@EntityScan(basePackages = "xxx.xxx.xxx")用以扫描@Entity
注解
采用方案二,新建一个配置类
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories(basePackages = "xxx.xxx.xxx")
@EntityScan(basePackages = "xxx.xxx.xxx")
public class JPAConfig {
}
问题解决。
但是为什么在
@SpringBootApplication
里scanBasePackages添加的包对于JPA不行呢?其他的组件明明可以扫描到啊,而且为什么启动类放在外层用默认的包也能扫描到?有时间还待研究...
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?