完美解决failed to configure a datasource: ‘url‘ attribute is not specified and no em

182 篇文章 98 订阅 ¥19.90 ¥99.00

一. 异常现象failed to configure a datasource: 'url' attribute is not specified and no em

我在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相关的配置!

二. failed to configure a datasource: ‘url‘ attribute is not specified and no em异常原因

其实这个异常在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

三. 解决办法failed to configure a datasource: 'url' attribute is not specified and no em


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

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

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

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

造成该异常的原因,是因为我这个项目中是分模块开发,但是这几个模块共同组成了一个项目,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进行激活配置,如下图所示:

-------------------------------------------------

如果是别的项目导致failed to configure a datasource: 'url' attribute is not specified and no em,

原因:项目新搭建的时候,引入了mybatis等框架,但是没有在yml等配置文件中配置链接,所以导致报错。

解决:1.删掉mybatis等框架的引用,2.配置数据库再链接。

  • 89
    点赞
  • 184
    收藏
    觉得还不错? 一键收藏
  • 27
    评论
评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值