問題描述
Spring Boot項目中運行之后,出現如下的錯誤:
*************************** 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).
或者出現@Value注解的值無法導入的時候,
Could not resolve placeholder 'elasticsearch.host' in value "${elasticsearch.host}"
可以用以下的解決方案
問題分析及解決方案
問題原因: Mybatis沒有找到合適的加載類,其實是大部分spring - datasource - url沒有加載成功,分析原因如下所示.
-
DataSourceAutoConfiguration會自動加載.
-
沒有配置spring - datasource - url 屬性.
-
spring - datasource - url 配置的地址格式有問題.
-
配置 spring - datasource - url的文件沒有加載.
網上給出了這幾種解決方案.
方案一 (解決原因1)
排除此類的autoconfig。啟動以后就可以正常運行。
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
方案二 (解決原因2)
在application.properties/或者application.yml文件中沒有添加數據庫配置信息.
spring: datasource: url: jdbc:mysql://localhost:3306/read_data?useUnicode=true&characterEncoding=UTF-8&useSSL=false username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver
方案三 (解決原因3)
在spring xml配置文件中引用了數據庫地址 所以需要對:等進行轉義處理.但是在application.properties/或者application.yml文件並不需要轉義,錯誤和正確方法寫在下面了.
#錯誤示例 spring.datasource.url = jdbc:mysql\://192.168.0.20\:1504/f_me?setUnicode=true&characterEncoding=utf8 #正確示例 spring.datasource.url = jdbc:mysql://192.168.0.20:1504/f_me?setUnicode=true&char
方案四 (解決原因4)
要在pom文件中<build></build>添加如下.來保證yml或者properties文件能被正常掃描到且加載成功.(intellij idea 運行時,掃描不到src文件夾(java文件夾)里面的配置文件)
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.yml</include> <include>**/*.properties</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.yml</include> <include>**/*.properties</include> </includes> <filtering>false</filtering> </resource> </resources>