本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看 活动链接
[已解决] Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.错误解决
问题描述:
SpringBoot项目启动时,出现如下异常信息:
[danube-chaos] [2020-08-07 14:36:30.759] [1596782172244_hugR] [MZhugR] [ERROR] [localhost-startStop-1] [org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter:42] -- []
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
//配置数据源失败:“url”属性未指定,且无法配置嵌入式数据源。
Reason: Failed to determine a suitable driver class
//原因:无法明确指定正确的驱动类(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).
//建议:
//如果如果需要加载嵌入式的数据库 (H2, HSQL or Derby),请将他放入路径中
//如果有数据库设置需要从指定配置文件中加载,需要调用该配置文件(目前没有活动的配置文件)
关键信息:
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
分析
我这里的项目并没有使用数据库,但是在一些依赖中引入了mysql、mybatis的依赖,导致springboot的启动,自动加载了一些依赖
而我没有进行配置数据库需要的信息
解决方案
我利用了下面的解决方案进行了解决。
首先,去pom文件中,将mysql、mybatis的依赖进行了排除
<exclusion>
<artifactId>mybatis-spring</artifactId>
<groupId>org.mybatis</groupId>
</exclusion>
<exclusion>
<artifactId>mysql-connector-java</artifactId>
<groupId>mysql</groupId>
</exclusion>
然后在springboot程序的入口类,将SpringBootApplication注解进行了修改
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class WebBootstrap {
public static void main(String[] args) {
SpringApplication.run(WebBootstrap.class, args);
}
}
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class}) 表示取消数据源的自动配置,不加载DataSourceAutoConfiguration类到Springboot容器中
重新启动项目,本地的一个问题解决
但是发布到测试环境,却一直没生效,最后发现是测试环境的代码一直没拉取到最新的代码,这是容器的问题,不在此讨论
最后通过更新代码进行了解决
其他解决方案
但是在实际中,可能还有各种原因导致此异常的出现
-
配置文件出现了遗漏/配置写错,确实没有这个配置数据 通过检查配置数据、添加数据源配置进行解决
-
配置文件中有配置,但还是报错 检查实际编译的目录下,也就是target中是否有完整的一个配置数据
-
在使用yml文件配置的时候在配置属性的前面习惯性的有一个或者几个空格或是一个“Tab” 在yml文件中配置的属性前面是不允许有缩进的,解决办法就是不缩进,该问题解决。改成如下。将缩进去掉即可,使用yml文件配置一定要注意格式,不然细节将会引起大错误
-
多模块项目,前面几种方式都没问题
如果是maven多模块项目,查看IDEA右上角Edit Configurations -> Use classpath of module,此栏应为 包含程序入口的 xxxApplication.java和application.yml 的module,也就是检查入口类和配置文件是否匹配到
基本上就是这几种可能,有其他的,欢迎在评论区讨论