一. 异常现象

我在Spring Boot中关联MySQL、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).


Process finished with exit code 1

看提示信息是说当前项目没有配置DataSource相关的配置!

二. 异常原因

其实这个异常在SpringBoot中是一个比较常见的异常,一般是因为SpringBoot自动配置时,检测到我们添加了MySQL、Oracle、Mybatis等和数据库相关的依赖包,结果我们的配置文件中却没有添加数据库相关的配置,比如:

spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db?characterEncoding=utf-8
username: root
password: root

三. 解决办法

针对以上原因造成的异常,可以采用如下办法解决:

  1. 在application.yml/applicaiton.properties中添加数据库相关配置;
  2. 在SpringBootApplication注解中进行数据库配置的排除,即@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})。

以上两种解决办法,可以解决一般的情况,但是还有一种情况比较特殊,就是当我们进行Spring Boot分模块开发,且不同模块中有多个application.yml或application.properties配置文件时造成的,如下图所示:

SpringBoot中“Failed to configure a DataSource: ‘url‘ attribute is not specified and no embedded datas_配置文件

我的这个案例中,我是把一个Spring Boot项目拆分成了shop-web、shop-service、shop-mapper等若干个模块,shop-mapper模块是数据库操作层,里面有个application.yml配置文件进行了数据库连接配置;shop-web模块中也有个application.yml文件,进行了端口、程序名等的配置。我把入口类写在shop-web模块中,然后进行项目启动,结果也产生了上面的异常信息。

SpringBoot中“Failed to configure a DataSource: ‘url‘ attribute is not specified and no embedded datas_配置文件_02

造成该异常的原因,是因为我这个项目中是分模块开发,但是这几个模块共同组成了一个项目,shop-web模块依赖shop-service,shop-service模块依赖shop-mapper,这样就相当于一个项目中产生了2个application.yml文件,web层的application.yml文件把mapper层的application.yml配置给覆盖掉了,所以产生了以上异常。

解决办法有2种思路:

  1. 把shop-web模块中的application.yml文件改成application.properties;
  2. 对不同模块中的配置文件,以application-*.yml的形式命名,比如application-mapper.yml,application-service.yml等,然后在最顶层的shop-web模块配置文件中,通过spring.profiles.active进行激活配置,如下图所示:

SpringBoot中“Failed to configure a DataSource: ‘url‘ attribute is not specified and no embedded datas_配置文件_03