欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot无法注入JpaRepository接口 (找不到指定Bean)

程序员文章站 2022-10-04 08:28:59
警告信息2020-07-15 14:09:28.821 WARN 11732 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Er...

警告信息

2020-07-15 14:09:28.821 WARN 11732 — [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘genController’: Unsatisfied dependency expressed through field ‘iGenTableService’; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘genTableServiceImpl’: Unsatisfied dependency expressed through field ‘genTableRepository’; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.bella.dao.GenTableRepository’ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

报错信息

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-07-15 14:09:29.199 ERROR 11732 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field genTableRepository in com.wondersgroup.healthcloud.service.impl.GenTableServiceImpl required a bean of type 'com.wondersgroup.healthcloud.dao.GenTableRepository' that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.wondersgroup.healthcloud.dao.GenTableRepository' in your configuration.

我的代码

SpringBoot无法注入JpaRepository接口 (找不到指定Bean)
SpringBoot无法注入JpaRepository接口 (找不到指定Bean)

解决思路

  • GenTableRepository -> Bean的定义没有问题
  • GenTableServiceImpl -> Bean的定义没有问题

两个Bean的定义都没问题 , 但是 GenTableServiceImpl 却无法在Spring容器中找到 GenTableRepository 这个Bean 。
注意 : 我们使用的是JpaRepository (spring-data-jpa)的功能 , 可能是项目框架中没有定义 JpaRepository 扫描包的位置 或 定义的位置和我们Class的位置不一致导致我们的 Bean 无法的注入到 Spring 容器中。

解决方案

  1. 项目中搜索 @EnableJpaRepositories 注解 (一般都会有,没有就自己添加)
  2. 添加我们的扫描包路径 (或将我们定义的JpaRepository放到项目指定的路径下)
  3. 重启项目就应该可以了
## 指定JpaRepositry扫描包的位置
@EnableJpaRepositories(basePackages = {"com.bella.dao.repository", "com.bella.dao"})

## 扫描的包可以定义多个 , basePackages 是一个 String 数组 (一定要保证你的Reposity在扫描路径中)
## 如果项目中没有定义 @EnableJpaRepositories , 可以在Application启动类上添加此注解 (或者自己定义一个 JpaConfig Bean 也可以)

## 指定Entity的扫描位置 (如果不指定 Entity Bean 也无法使用)
@EntityScan(basePackages = { "com.bella.domain" })

本文地址:https://blog.csdn.net/qq_24958783/article/details/107359799