Spring Boot连接MySQL遇DataSource与entityManagerFactory配置错误求助
Spring Boot连接MySQL数据库配置错误排查
我正在跟随in28minutes课程,尝试用Spring Boot连接MySQL(不使用H2),但始终遇到配置错误,尝试多种方法都无法解决。
项目代码与配置
LearnMySqlDockerApplication.java
package com.in28min.LearnMySQLDocker; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class }) @ComponentScan("com.in28min.LearnMySQLDocker.courses") @Configuration @EnableJpaRepositories(basePackages = "com.in28min.LearnMySQLDocker.courses.repository") public class LearnMySqlDockerApplication { public static void main(String[] args) { SpringApplication.run(LearnMySqlDockerApplication.class, args); } }
CourseRepository.java
package com.in28min.LearnMySQLDocker.courses.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.in28min.LearnMySQLDocker.courses.bean.Course; public interface CourseRepository extends JpaRepository<Course, Long>{ }
CourseController.java
package com.in28min.LearnMySQLDocker.courses.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.in28min.LearnMySQLDocker.courses.bean.Course; import com.in28min.LearnMySQLDocker.courses.repository.CourseRepository; @RestController public class CourseController { @Autowired private CourseRepository repository; // http://localhost:8080/courses @GetMapping("/courses") public List<Course> getAllCourses() { return repository.findAll(); } // http://localhost:8080/courses/1 @GetMapping("/courses/{id}") public Course getCourseDetails(@PathVariable long id) { return repository.findById(id).get(); } /* POST http://localhost:8080/courses { "name": "Learn DevOps", "author": "in28minutes" }*/ //POST - Create a new resource (/courses) @PostMapping("/courses") public void createCourse(@RequestBody Course course){ repository.save(course); } /* PUT - http://localhost:8080/courses/100001 { "id": 100001, "name": "Learn Microservices 2", "author": "in28minutes" } */ //PUT - Update/Replace a resource (/courses/1) @PutMapping("/courses/{id}") public void updateCourse(@PathVariable long id, @RequestBody Course course){ repository.save(course); } //DELETE - Delete a resource (/courses/1) @DeleteMapping("/courses/{id}") public void deleteCourse(@PathVariable long id){ repository.deleteById(id); } // docker run --detach // --env MYSQL_ROOT_PASSWORD=dummypassword // --env MYSQL_USER=courses-user // --env MYSQL_PASSWORD=dummycourses // --env MYSQL_DATABASE=courses // --name mysql // --publish 3306:3306 mysql:5.7 }
Course.java
package com.in28min.LearnMySQLDocker.courses.bean; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; @Entity public class Course { @Id @GeneratedValue private long id; //@Column(name="course_name") private String name; private String author; public Course() { } public Course(long id, String name, String author) { super(); this.id = id; this.name = name; this.author = author; } public long getId() { return id; } public String getName() { return name; } public String getAuthor() { return author; } @Override public String toString() { return "Course [id=" + id + ", name=" + name + ", author=" + author + "]"; } }
application.properties
spring.application.name=Learn-MySQL-Docker #logging.level.org.springframework=DEBUG #management.endpoints.web.exposure.include=* management.endpoints.web.exposure.include=health,metrics #spring.datasource.url=jdbc:h2:mem:testdb spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost:3306/courses spring.datasource.username=courses-user spring.datasource.password=dummycourses spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect #courses-user@localhost:3306
依赖说明
pom.xml已添加以下依赖:spring-boot-starter-data-jpa、mysql-connector-j、hibernate-entitymanager、mysql-connector-java、spring-boot-starter-web
遇到的错误
Field repository in com.in28min.LearnMySQLDocker.courses.controller.CourseController required a bean named 'entityManagerFactory' that could not be found.Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
解决方案
核心问题是手动排除了DataSourceAutoConfiguration,打断了Spring Boot自动配置数据源和JPA组件的流程,导致无法初始化entityManagerFactory等必要Bean。
修复步骤:
- 移除启动类中的数据源自动配置排除项
修改后的LearnMySqlDockerApplication.java:
package com.in28min.LearnMySQLDocker; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication @ComponentScan("com.in28min.LearnMySQLDocker.courses") @EnableJpaRepositories(basePackages = "com.in28min.LearnMySQLDocker.courses.repository") public class LearnMySqlDockerApplication { public static void main(String[] args) { SpringApplication.run(LearnMySqlDockerApplication.class, args); } }
- 移除配置文件中的自动配置排除项
删除application.properties中这一行:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
清理冗余依赖
mysql-connector-j和mysql-connector-java是同一依赖的不同版本命名,保留mysql-connector-j即可,移除mysql-connector-java避免冲突。验证MySQL容器状态
确保MySQL容器正在运行:
docker ps
若未运行,执行启动命令:
docker run --detach \ --env MYSQL_ROOT_PASSWORD=dummypassword \ --env MYSQL_USER=courses-user \ --env MYSQL_PASSWORD=dummycourses \ --env MYSQL_DATABASE=courses \ --name mysql \ --publish 3306:3306 mysql:5.7
原理说明
Spring Boot会根据spring-boot-starter-data-jpa和MySQL驱动依赖,自动识别application.properties中的数据源配置,创建DataSource、EntityManagerFactory等核心Bean。排除DataSourceAutoConfiguration会直接中断这个自动配置流程,导致数据库连接相关组件无法初始化,进而触发报错。
内容的提问来源于stack exchange,提问作者Oh Suk
相关产品推荐
相关产品推荐

