当 Spring Boot 服务依赖 MySQL 但启动后立即停止时,通常有以下几种可能原因:
确保 application.properties
或 application.yml
中有正确的数据库配置:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 如果是 JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
确保 pom.xml
或 build.gradle
中有正确的 MySQL 驱动依赖:
Maven:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version> <!-- 使用适合你MySQL版本的驱动 -->
</dependency>
Gradle:
implementation 'mysql:mysql-connector-java:8.0.28'
查看启动日志,通常会有更详细的错误信息。常见错误包括:
- java.sql.SQLException: Access denied for user
- Communications link failure
- Table 'xxx' doesn't exist
确保 MySQL 服务正在运行:
# Linux/Mac
sudo service mysql status
# Windows
net start | find "MySQL"
如果问题紧急,可以临时禁用数据库初始化进行测试:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
logging.level.org.springframework=DEBUG
logging.level.org.hibernate=DEBUG
测试数据库连接: 使用 MySQL 客户端工具测试是否能连接数据库
检查数据库权限: 确保应用使用的数据库用户有足够的权限
检查数据库版本兼容性: 确保 MySQL 驱动版本与数据库版本兼容
检查网络连接: 如果是远程数据库,确保网络可达且端口开放
错误1:java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed
# 解决方案:在连接URL中添加参数
spring.datasource.url=jdbc:mysql://localhost:3306/db?allowPublicKeyRetrieval=true&useSSL=false
错误2:The server time zone value 'xxx' is unrecognized
# 解决方案:指定时区
spring.datasource.url=jdbc:mysql://localhost:3306/db?serverTimezone=UTC
错误3:Table 'database.hibernate_sequence' doesn't exist
# 解决方案:对于MySQL 8+,使用以下配置
spring.jpa.hibernate.use-new-id-generator-mappings=false
如果以上方法都不能解决问题,建议提供完整的错误日志以便更精确地诊断问题。