1. 首页
  2. 软件开发
  3. JAVA
  4. spring boot3配置dynamic多数据源,报错url找不到,解决方案

spring boot3配置dynamic多数据源,报错url找不到,解决方案

  • 发布于 2024-08-13
  • 0 次阅读

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

我在编写 springboot 项目时尝试使用 dynamic-datasource 实现多数据库连接

运行项目时报错退出

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

报错如下

***************************
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

可能存在的问题

1.pom 依赖导入情况

我当时遇到的就是这个问题

请注意,如果是 springboot3 项目,导入的包是下面这样

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
    <version>4.3.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.9</version>
</dependency>

如果是 springboot2 项目

<!-- 多数据源 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
</dependency>
 
<!-- druid 官方 starter -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
</dependency>

忘记自己 springboot 版本,可以在 pom 文件开头找(如下)

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
2.application.yml 文件是否写对

按照下面这种格式写

server:
  port: 9090
#    数据库
spring:
  datasource:
    dynamic:
      primary: mysql
      strict: false
      datasource:
        mysql:
          url: jdbc:mysql://localhost:3306/ias_info?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
          username: root
          password: 123
          driver-class-name: com.mysql.cj.jdbc.Driver
        mysql1:
          url: jdbc:mysql://cent:3306/alarm?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2b8
          username: root
          password: 123
          driver-class-name: com.mysql.cj.jdbc.Driver

关于其它问题

推荐几个大佬的博客,希望有帮助

spring boot 配置 dynamic 多数据源,报错 url 找不到,解决方案_java dev profile 里配置了 url 找不到 - CSDN 博客

完美解决 failed to configure a datasource: ‘url‘ attribute is not specified and no em_failed to configure a datasource: 'url' attribute -CSDN 博客

【精 · 超详细】SpringBoot 配置多个数据源(连接多个数据库)_springboot 连接多个数据源 - CSDN 博客