Spring Boot启动报错:UserService构造所需UserRepository类型Bean未找到
你遇到的报错核心是Spring容器无法识别并注册你定义的UserRepository接口为可用Bean,存在3处需要修正的配置:
1. 启动类补充JPA相关扫描注解
Spring Data JPA的Repository接口无法仅通过@ComponentScan完成注册,需要单独添加@EnableJpaRepositories注解扫描Repository包,同时添加@EntityScan注解扫描JPA实体类所在包。
修改后的TutortekApplication.kt代码如下:
package com.karbal.tutortek import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.data.jpa.repository.config.EnableJpaRepositories import org.springframework.boot.autoconfigure.domain.EntityScan @SpringBootApplication(scanBasePackages = ["controllers", "entities", "repositories", "services"]) @EnableJpaRepositories(basePackages = ["repositories"]) @EntityScan(basePackages = ["entities"]) class TutortekApplication fun main(args: Array<String>) { runApplication<TutortekApplication>(*args) }
优化提示:如果将
controllers、entities、repositories、services四个包都移动到启动类所在的com.karbal.tutortek包下作为子包,就可以删除上述所有手动指定包路径的配置,Spring Boot会自动扫描启动类所在包及子包下的所有组件。
2. 修正User实体类的@Id注解导包
你当前导入的是Spring Data通用的@Id注解,JPA规范要求使用javax.persistence包下的主键注解,否则JPA无法识别实体类主键。
修改后的User.kt代码如下:
package entities import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id import javax.persistence.Table @Entity @Table(name = "users") data class User( @Id @GeneratedValue(strategy = GenerationType.AUTO) val id: Long?, val name: String )
删除原有import org.springframework.data.annotation.Id的导入语句
3. 修正UserRepository中Query注解配置
你当前写的SQL是原生SQL语句,@Query注解默认解析JPQL语句,需要额外指定nativeQuery = true属性才可以运行原生SQL,同时删除无用的@Component导入,@Repository已经具备组件注册能力。
修改后的UserRepository.kt对应代码如下:
package repositories import entities.User import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository @Repository interface UserRepository : CrudRepository<User, Long>{ @Query(value = "SELECT * FROM users", nativeQuery = true) fun getAllUsers(): List<User> }
完成以上3处修改后重启应用即可正常注册UserRepository Bean,解决当前报错。
内容的提问来源于stack exchange,提问作者KapitaiN

