相关推荐recommended
springboot报错Error creating bean with name ‘dataSource‘的解决方案
作者:mmseoamin日期:2024-03-20

问题描述:

在学习到黑马的学成在线微服务项目时,运行内容模块的服务时报错如下:

org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'dataSource': 
Unsatisfied dependency expressed through field 'basicProperties'; 
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties':
Instantiation of bean failed; 
nested exception is org.springframework.beans.BeanInstantiationException: 
Failed to instantiate [org.springframework.boot.autoconfigure.jdbc.DataSourceProperties]: 
Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseType
	

报错异常分析:

Spring应用程序中名为“dataSource”的bean的依赖项注入存在问题。具体问题在于“dataSource”bean的“basicProperties”字段。此字段有一个未满足的依赖项。

嵌套异常进一步解释了此错误的根本原因,该异常表示“DataSourceProperties”bean的实例化失败。它遇到“BeanInstanceException”,其中“DataSourceProperties”类的构造函数引发了异常。此异常的根本原因是类“org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType”的“NoClassDefFoundError”。

“NoClassDefFoundError”表明运行时在类路径上找不到类“EmbeddedDatabaseType”。这个类通常是spring Framework中“spring-jdbc”模块的一部分。

要解决此问题,应确保在项目的生成配置中正确包含必要的依赖项。具体来说,您需要确保在构建文件(例如,Maven的pom.xml或Gradle的build.Gradle)中正确指定了“spring-jdbc”依赖项。

解决问题:

对于Maven,您可以在pom.xml中添加以下依赖项:


    org.springframework.boot
    spring-boot-starter-jdbc

对于Gradle,那可以在build.gradle中添加一下依赖:

implementation 'org.springframework.boot:spring-boot-starter-jdbc'