springboot2.0配置多环境数据源时application.yml文件问题探讨

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/xuruanshun/article/details/102603351

我在使用springboot2.0配置多环境数据源时,出现了一些问题:

首先,我在application.yml文件中配置多数据源:

spring:
  datasource:
    test01:
      url: jdbc:mysql://localhost:3306/test01?serverTimezone=UTC
      username: root
      password: 123
      driver-class-name: com.mysql.jdbc.Driver

    test02:
      url: jdbc:mysql://localhost:3306/test02?serverTimezone=UTC
      username: root
      password: 123
      driver-class-name: com.mysql.jdbc.Driver

访问时会报错:

java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.

报错原因,是因为springboot的版本问题,2.0之后的版本红色的部分与之前的版本不同,

详细原因可参考:https://blog.csdn.net/shenzhou_yh/article/details/100689804

所以我把配置文件修改成:

spring:
  datasource:
    test01:
      jdbc-url: jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
      username: root
      password: 123
      driver-class-name: com.mysql.jdbc.Driver

    test02:
      jdbc-url: jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
      username: root
      password: 123
      driver-class-name: com.mysql.jdbc.Driver

这样就可以访问成功了。

还有一个问题:springboot默认加载的数据源格式:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
    username: root
    password: 123
    driver-class-name: com.mysql.jdbc.Driver

spring.datasource.url  格式是固定的,多数据源时的配置文件 spring.datatasource.test01.url 中, spring.datatasource.test01这一部分是自定义的,springboot默认是无法加载的,需要指定数据源才可以加载。

而且有意思的是,说springboot2.0版本不能识别spring.datasource.url,只能识别spring.datasource.jdbc-url,我试过,在单数据源情况下,其实前者是可以识别的,只有在多数据源情况下,才不能识别前者,只识别后者,可能是springboot的bug,也可能是我不知道的原因。

猜你喜欢

转载自blog.csdn.net/xuruanshun/article/details/102603351