1. 程式人生 > 實用技巧 >Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

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

問題:

  

問題分析及解決方案


問題原因: Mybatis沒有找到合適的載入類,其實是大部分spring - datasource - url沒有載入成功,分析原因如下所示.

  1. DataSourceAutoConfiguration會自動載入.

  2. 沒有配置spring - datasource - url 屬性.

  3. spring - datasource - url 配置的地址格式有問題.

  4. 配置 spring - datasource - url的檔案沒有載入.

方案一 (解決原因1)

排除此類的autoconfig。啟動以後就可以正常執行。

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
方案二 (解決原因2)

在application.properties/或者application.yml檔案中沒有新增資料庫配置資訊.

spring:
  # 配置資料來源
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/my_shiro?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
方案三 (解決原因3)

在spring xml配置檔案中引用了資料庫地址 所以需要對:等進行轉義處理.但是在application.properties/或者application.yml檔案並不需要轉義,錯誤和正確方法寫在下面了.

//錯誤示例
spring.datasource.url = jdbc:mysql\:localhost:3306/my_shiro?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false
//正確示例
spring.datasource.url = jdbc:mysql://localhost:3306/my_shiro?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false
方案四 (解決原因4)

配置了主從資料庫,卻沒有寫讀取druid的配置,找不到url,還是寫成方案二吧,如果實在要用,自己搜教程

spring:
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        druid:
            # 主庫資料來源
            master:
                url: jdbc:mysql://localhost:3306/my_shiro?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
                username: root
                password: root
            # 從庫資料來源
            slave:
                # 從資料來源開關/預設關閉
                enabled: false
                url: 
                username: 
                password: 

方案五 (解決原因5)

yml或者properties檔案沒有被掃描到,需要在pom檔案中<build></build>新增如下.來保證檔案都能正常被掃描到並且載入成功.

<!-- 如果不新增此節點mybatis的mapper.xml檔案都會被漏掉。 -->
<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.yml</include>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.yml</include>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
    </resource>
</resources>