1. 程式人生 > 實用技巧 >Spring boot 啟動提示資料來源錯誤

Spring boot 啟動提示資料來源錯誤

在啟動 Spring Boot 的專案的時候提示資料來源未配置的錯誤。

09:52:08.333 [main] DEBUG o.s.b.d.LoggingFailureAnalysisReporter - Application failed to start due to an exception
org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
	at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:233)
	at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder(DataSourceProperties.java:174)

Spring 會提示你完整的導致啟動錯誤的資訊是:

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

錯誤分析

從上面的啟動資訊來看,已經說得非常清楚了,就是因為你配置了 Spring 的資料元件,但是你沒有配置相應的資料來源。

因為這個會導致你的啟動失敗。

解決辦法

有下面的集中解決辦法:

加入 H2 包

最簡單的解決辦法就是在依賴中新增 H2 的資料庫,如果你使用 Spring Batch 的話,這個元件也是需要的,因為 Spring 會使用 H2 為資料來源。

新增資料來源配置

如果你已經添加了資料庫驅動,例如你添加了 mysql 的資料庫驅動。

那麼你需要制定 Mysql 的資料庫連線引數。

spring.datasource.url=jdbc:mysql://localhost:3306/myDb
spring.datasource.username=user1
spring.datasource.password=pass
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

在啟動時候不載入資料來源配置。

你可用在啟動的時候不載入資料來源配置。

可用在啟動類上面,新增下面的註解。

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})

你也可以在啟動配置檔案上面,新增下面的內容,這樣能夠保證你在啟動的時候不載入資料來源配置類。

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAuto

https://www.ossez.com/t/spring-boot/504