按Spring官方文档配置MySQL数据访问报错,提示未找到UserRepository类型Bean
解决方案操作步骤
- 完全删除你手动编写的
ApplicationConfiguration配置类,Spring Boot 自带的JPA、DataSource自动配置完全覆盖该场景,手动配置反而会覆盖自动配置逻辑,且你编写的配置中存在包名大小写错误、驱动类过时等问题。 - 删除启动类上额外添加的
@EnableJpaRepositories注解,删除UserRepository接口上的@Repository注解:spring-data-jpa会自动识别继承了CrudRepository的接口,只要在启动类默认扫描范围内就会自动生成实现类并注册为Bean。 - 检查
User实体类注解是否完整,示例如下:
package com.example.testfield; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private String email; // getter、setter方法 }
- 替换
application.properties中的配置为以下内容,替换对应数据库、账号、密码参数:
spring.datasource.url=jdbc:mysql://localhost:3306/你的数据库名称?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true spring.datasource.username=你的数据库账号 spring.datasource.password=你的数据库密码 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
- 检查所有业务类的包路径:启动类、User实体、UserRepository、MainController都必须放在
com.example.testfield包或其子包下,注意包名全部为小写,禁止出现大小写混写的错误路径。 - 执行
mvn clean命令清空之前的编译产物,重新启动项目即可正常运行。
内容的提问来源于stack exchange,提问作者Michal Ruszkowski
相关产品推荐
相关产品推荐

