SpringBoot集成Mybatis等可能会报错如下:
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
解决方法:
针对Spring Boot启动时报错Failed to configure a DataSource: 'url' attribute is not specified and no embedded
,以下是几种常见解决方案:
1. 不需要链接数据库
适用场景:项目不需要数据库(如仅创建 REST API),则排除数据源自动配置。
解决:在启动类或配置文件中禁用数据源自动配置:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
或在 application.properties
中配置:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
2. 添加数据库配置
原因:项目依赖了spring-boot-starter-data-jpa
或spring-boot-starter-jdbc
,但未配置数据库连接信息。
解决:在application.properties
或application.yml
中添加数据库配置:
# MySQL 示例
spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# YAML 格式
spring:
datasource:
url: jdbc:mysql://localhost:3306/your_database
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
3. yml文件格式不正确
还有一种错误,是基于第二种的,自己配置了数据源发现还是报同样的错误,新手也很容易犯的错误,就是在使用yml文件配置的时候在配置属性的前面习惯性的有一个或者几个空格或是一个“Tab”,如下:
在yml文件中配置的属性前面是不允许有缩进的,解决办法就是不缩进,该问题解决。改成如下。将缩进去掉即可,
使用yml文件配置一定要注意格式
4. 使用嵌入式数据库
适用场景:希望使用内存数据库(如 H2、HSQLDB)。
解决:
- 添加嵌入式数据库依赖(如 H2):
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
- 配置嵌入式数据库 URL:
spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password=
5. 检查依赖项
适用场景:误添加了数据库相关依赖。
解决:移除不必要的依赖(如 pom.xml
或 build.gradle
中的 spring-boot-starter-data-jpa
或 spring-boot-starter-jdbc
):
<!-- 移除示例 -->
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> -->
6. 多环境配置检查
适用场景:使用了 profile
但未激活。
解决:确保激活的 profile
中包含正确的数据库配置:
# 激活 dev 环境
spring.profiles.active=dev
并检查对应的 application-dev.properties
文件是否配置了数据源。
7. 检查数据库服务状态
适用场景:配置正确但数据库服务未启动。
解决:确保本地或远程数据库服务正常运行(如 MySQL、PostgreSQL)。
8. 其他尝试
- maven重新编译一下,clean再install项目
- naco集群重启一下
- 将resource标记为资源目录
- 还有一种情况, dataSource的上一层及不是spring也会报这个错
- 还有几种情况,注意检查各种配置集中的断线与下划线,比如yml文件名字是短线还是下划线,数据库名是短线还是下划线等
总结步骤:
- 确认需求:是否需要数据库?
- 是 → 配置数据库或使用嵌入式数据库。
- 否 → 排除自动配置或移除依赖。
- 检查依赖和配置:确保依赖和配置文件一致。格式和url没问题。
- 重启应用:修改后重新启动应用验证。
根据具体场景选择合适方案即可解决问题。