springboot项目报错: 'url' attribute is not specified and no embedded datasource could be configured解决方案

在springboot项目中使用JDBC,发现报如下错误:
springboot项目报错: 'url' attribute is not specified and no embedded datasource could be configured解决方案_第1张图片
原因:
   由于在springboot项目中导入了JDBC应用依赖,springboot会通过autoconfig去读取数据源信息,但是此时在springboot的默认配置文件application.properties或者application.yml中没有配置数据源。

解决办法:
  在springbot的启动类的@SpringBootApplication中添加exclude = {DataSourceAutoConfiguration.class}
springboot项目报错: 'url' attribute is not specified and no embedded datasource could be configured解决方案_第2张图片


  出现上述情况是因为在springboot默认的配置文件中没有配置数据源,而是使用了自定义的配置文件,如下所示的application-dev.yml文件。

springboot项目报错: 'url' attribute is not specified and no embedded datasource could be configured解决方案_第3张图片
application-dev.yml文件中的配置:

spring:
  profiles:
    active: dev
# 激活application-dev.yml

  datasource:
    username: xxx
    password: xxx
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver

  值得一提的是,如果在默认配置文件中配置数据源或者在默认配置文件中去激活自定义的配置文件时,就不会报上面的错误。

【1】直接在默认配置文件中配置数据源信息

application.yml:

spring:
  datasource:
    username: xxx
    password: xxx
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver

【2】在默认配置文件中激活指定配置文件方式

application.yml:

spring:
  profiles:
    active: dev

application-dev.yml:

spring:
  datasource:
    username: xxx
    password: xxx
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver

你可能感兴趣的:(异常处理)