场景描述
异常现象
***************************
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).
出现上述现象的原因是:在 pom.xml 中加入了 JPA , 项目启动时默认执行 JPA 的自动配置,构建 JPA DataSource 的 bean 注入到 spring 容器中。但在执行时没有找到数据库的配置信息,所以就出现了异常。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
解决办法
解决上述异常有两种方式:(1)提供数据库的配置信息,完成自动配置。(2)直接禁止 JPA 的自动配置。
(完成自动配置)在 application.properties 中添加数据信息即可。
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
(禁止自动配置)
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
或者
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
参考链接
https://www.baeldung.com/spring-boot-failed-to-configure-data-source