解决错误无法自动配置数据源:未指定“spring.datasource.url”

x33g5p2x  于2022-09-28 转载在 Spring  
字(2.2k)|赞(0)|评价(0)|浏览(634)

本教程将帮助您解决错误 Failed to auto-configure a DataSource: ‘spring.datasource.url’ is not specified in your Spring Boot applications。

简而言之,如果您在 pom.xml 文件中配置了spring-boot-starter-data-jpa 依赖项并且您尚未在 application.properties 中定义任何数据源 url,则会发生此错误

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

这将导致以下错误:

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

让我们看看如何解决这个问题。

如果不需要,请删除 JPA 启动器

首先,如果您在 pom.xml 中错误地添加了 JPA starter,或者如果您将持久性存储从 RDBMS 更改为 MongoDB(例如),只需删除 jpa starter 即可解决问题:

<!-- Remove this 
<dependency> 
   <groupId>org.springframework.boot</groupId> 
   <artifactId>spring-boot-starter-data-jpa</artifactId> 
</dependency> 
-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

在 application.properties 中包含数据库配置

第二个选项,如果您打算使用像 MySQL 这样的外部数据库,请确保您的 application.properties 包含完整的配置。还要确保您的 pom.xml 文件具有适用于您的数据库的 JDBC 驱动程序:

spring.datasource.url=jdbc:mysql://localhost/demodb 
spring.datasource.username=admin 
spring.datasource.password=password 
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect spring.jpa.show-sql=true 
spring.jpa.hibernate.ddl-auto=update

还有 pom.xml 文件:

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

使用嵌入式数据库

最后,值得一提的是,使用嵌入式数据库时,无需在 application.properties 中指定连接设置。事实上,Spring Boot 会为其使用一些默认值。只需确保您的 pom.xml 中有 JDBC 内存数据库的依赖项。 H2 数据库示例:

<dependency> 
   <groupId>org.springframework.boot</groupId> 
   <artifactId>spring-boot-starter-data-jpa</artifactId> 
</dependency> 
<dependency> 
   <groupId>com.h2database</groupId> 
   <artifactId>h2</artifactId> 
   <scope>runtime</scope> 
</dependency>

相关文章

微信公众号

最新文章

更多