創(chuàng)建Spring Boot應(yīng)用報(bào)錯(cuò):Failed to configure a DataSource: 'url' attribute is not specified and no embedd

1. 問(wèn)題

初學(xué)者在使用IDEA創(chuàng)建Spring Boot應(yīng)用后直接運(yùn)行會(huì)遇到報(bào)錯(cuò):Failed to configure a DataSource: 'url' attribute is not specified and no embedd,如下圖:


IDEA運(yùn)行Spring Boot應(yīng)用報(bào)錯(cuò)內(nèi)容

2. 解決方案:

1)方案一:適用沒(méi)有使用數(shù)據(jù)庫(kù)應(yīng)用,詳細(xì)解決方案如下:

@SpringBootApplication中加exclude屬性阻止Spring Boot自動(dòng)配置JDBC。

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
public class XXXSpringApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserManagerApplication.class, args);
    }
}

2)方案二:適用應(yīng)用中使用了數(shù)據(jù)庫(kù),詳細(xì)解決方案如下:

通過(guò)在application.properties文件中配置數(shù)據(jù)庫(kù)的信息來(lái)解決這個(gè)問(wèn)題,詳細(xì)的配置方案如下:

  • 1. 在項(xiàng)目中找到application.properties文件,具體路徑:src/main/resources/applicatio.properties,請(qǐng)參考下圖:

application.properties項(xiàng)目路徑
  • 2. 在文件中配置數(shù)據(jù)的詳細(xì)信息

如上圖所示,新建的工程的application.properties初始是一個(gè)空文件,沒(méi)有任何內(nèi)容,請(qǐng)復(fù)制下面的配置信息到文件中

#數(shù)據(jù)庫(kù)相關(guān)配置
spring.datasource.url=jdbc:mysql://localhost:3306/databaseName
spring.datasource.username= userName
spring.datasource.password= password
  • 第一行的spring.datasource.url是數(shù)據(jù)庫(kù)的地址,3306是MySql默認(rèn)的本地端口,databaseName需要替換成您自己創(chuàng)建的數(shù)據(jù)庫(kù)名稱;
  • 第二行和第三行中spring.datasource.usernamespring.datasource.password分別聲明了數(shù)據(jù)庫(kù)的用戶名賬號(hào)和密碼;

3. 原因分析:

原因很明顯,就是在應(yīng)用中沒(méi)有配置datasource的一些相關(guān)屬性。Spring Boot的自動(dòng)配置功能會(huì)根據(jù)加入classpath的依賴,嘗試自動(dòng)配置bean。因?yàn)槲覀兗尤肓薺dbc這個(gè)依賴,Spring Boot就會(huì)嘗試自動(dòng)配置JDBC DataSource。但問(wèn)題是Spring Boot還沒(méi)有得到足夠的信息進(jìn)行自動(dòng)配置。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容