目錄
- 一、報錯日志
- 二、原因分析
- 三、問題排查
- 四、解決方案
- 方案一:如果項目不需要數據庫相關信息就排除此類的autoconfig
- 方案二:配置文件添加數據庫鏈接信息
- 方案三:配置pom.xml中yml或者properties掃描
一、報錯日志
***************************
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 classAction: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
二、原因分析
根據報錯日志分析是在 SpringBoot
項目啟動的時候沒有找到 database
數據庫連接地址,我們知道在 SpringBoot
啟動的時候會默認加載org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
這個類,而 DataSourceAutoConfiguration
類使用了 @Configuration
注解向spring注入了dataSource bean
,又因為項目中并沒有關于 dataSource
相關的配置信息,所以當spring創建dataSource bean時因缺少相關的信息就會報錯。
三、問題排查
-
檢查
pom.xml
項目數據庫jar
是否引用; -
查看
.properties
或.yml
配置文件是否配置數據庫鏈接池; -
查看
spring - datasource - url
配置的地址格式錯誤需要轉義等; -
yml
或者properties
文件可能沒有被掃描到(情況比較少,如果按照標準命名都會被默認掃描);
四、解決方案
方案一:如果項目不需要數據庫相關信息就排除此類的autoconfig
在 @SpringBootApplication
注解上加上 exclude
,解除自動加載DataSourceAutoConfiguration
。
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
springboot啟動類加上這個啟動以后就可以正常運行。完整代碼:
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class Application {public static void main(String[] args) {SpringApplication.run(Application, args);}
}
方案二:配置文件添加數據庫鏈接信息
.properties
文件添加數據庫配置信息(以mysql為例):
spring.datasource.name=test
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
.yml
文件添加數據庫配置信息(已mysql為例):
spring:datasource:name: testurl: jdbc:mysql://localhost:3306/testusername: rootpassword: 123456driver-class-name: com.mysql.jdbc.Driver
方案三:配置pom.xml中yml或者properties掃描
需要在 pom
文件中 <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>