UnsatisfiedDependencyException NoSuchBeanDefinitionException

本文分析了Spring框架中出现的UnsatisfiedDependencyException与NoSuchBeanDefinitionException异常原因,并提供了详细的排查步骤,帮助开发者快速定位并解决相关问题。

UnsatisfiedDependencyException NoSuchBeanDefinitionException

原文地址:
http://blog.youkuaiyun.com/u011731544/article/details/78988969

2018-01-06 15:09:14,361 WARN [org.springframework.web.context.support.XmlWebApplicationContext] - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘blogController’: Unsatisfied dependency expressed through field ‘categoryService’; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.ssm.blog.service.CategoryService’ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.ssm.blog.service.CategoryService’ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

上面这段异常说创建blogController的时候失败了,UnsatisfiedDependencyException是依赖不满足抛出的异常,因为我在Controller中注入了categoryService。接着NoSuchBeanDefinitionException表示没有这样一个bean,也就是说我的categoryService没有生成bean。

遇到这种情况,要检查一下以下配置:

1) service接口实现类上有没有加@Service注解,注解是不是引用的spring的类?不要导错包

2) 接口有没有写实现类,实现类是实现的对应接口么?比如CategoryServiceImpl implements CategoryDAO 一不小心根据自动提示,本来应该实现CategoryService,结果实现了CategoryDAO

3) 有没有扫描Service所在的包

  1. <!– 启动自动扫描 –>  
  2.     <context:component-scan base-package=“com.ssm.blog.*”>  
  3.         <!– 制定扫包规则 ,不扫描@Controller注解的JAVA类 –>  
  4.         <context:exclude-filter type=“annotation” expression=“org.springframework.stereotype.Controller”/>  
  5.     </context:component-scan>  
<!-- 启动自动扫描 -->
    <context:component-scan base-package="com.ssm.blog.*">
        <!-- 制定扫包规则 ,不扫描@Controller注解的JAVA类 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
注意这段配置要加在spring父容器中而不是springMVC子容器。因为父容器无法访问自容器的对象。



Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ODataConnectorImpl': Unsatisfied dependency expressed through field 'messages'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'weibaobiaoMessages': Unsatisfied dependency expressed through field 'securityService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'amsSecurityService': Unsatisfied dependency expressed through field 'securityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityManager' defined in class path resource [security-service.xml]: Cannot resolve reference to bean 'amsAuthorizationRealm' while setting bean property 'realm'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'amsAuthorizationRealm': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userServiceImpl': Unsatisfied dependency expressed through field 'customerService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customerServiceImpl': Unsatisfied dependency expressed through field 'metadataService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'defaultMetadataServiceImpl': Unsatisfied dependency expressed through field 'zxtbTask'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'zxtbTask': Unsatisfied dependency expressed through field 'redisDistributeLock'; nested exception is org.springframework.beans.f
07-09
2025-03-27 15:47:51.709 ERROR 24032 - [restartedMain] [o.s.b.web.embedded.tomcat.TomcatStarter,onStartup,61] : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'registration' defined in class path resource [com/cloudweb/oa/security/BeanConfig.class]: Unsatisfied dependency expressed through method 'registration' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jwtFilter': Unsatisfied dependency expressed through field 'jwtUtil'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jwtUtil': Unsatisfied dependency expressed through field 'userCache'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userCache': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userServiceImpl': Unsatisfied dependency expressed through field 'userGroupService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'groupServiceImpl': Unsatisfied dependency expressed through field 'departmentService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'departmentServiceImpl': Unsatisfied dependency expressed through field 'deptUserService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'deptUserServiceImpl': Unsatisfied dependency expressed through field 'userSetupService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userSetupServiceImpl': Unsatisfied dependency expressed through field 'roleService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'roleServiceImpl': Unsatisfied dependency expressed through field 'rolePrivService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'rolePrivServiceImpl': Unsatisfied dependency expressed through field 'userOfRoleService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userOfRoleServiceImpl': Unsatisfied dependency expressed through field 'syncUtil'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.cloudweb.oa.api.ISyncUtil' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
03-28
分析报错:org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisSubscribeListener': Unsatisfied dependency expressed through field 'alarmListener'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'alarmListener': Unsatisfied dependency expressed through field 'alarmTask'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'alarmTask': Unsatisfied dependency expressed through field 'alarmReceiver'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'alarmReceiver': Unsatisfied dependency expressed through field 'eventAlarmLogInsertTask'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'eventAlarmLogInsertTask': Unsatisfied dependency expressed through field 'eventLogAlarmService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'eventLogAlarmService': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'eventLogAlarmMapper' defined in URL [jar:file:/opt/evo/evo-common/evo-event/evo-event.jar!/com/dahua/evo/event/business/mapper1/EventLogAlarmMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shardingDataSource' defined in class path resource [com/dahua/evo/event/config/DataSourceConfig1.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'shardingDataSource' threw exception; nested exception is
最新发布
08-15
<think>我们正在解决Spring框架中的`UnsatisfiedDependencyException`错误。根据引用内容,这个异常通常发生在Spring应用运行时,表示某个bean无法满足其依赖关系。下面将详细分析原因并提供解决方案。 ### 错误原因分析 1. **XML配置错误**(引用[1]): - 在XML配置文件中可能存在错误的依赖注入配置,例如错误的属性名或引用不存在的bean。 2. **类路径问题**(引用[2]): - 项目打包成JAR后运行时,可能缺少必要的类(`ClassNotFoundException`),导致依赖无法满足。 3. **循环依赖或深层依赖问题**(引用[3]): - 异常堆栈显示多层嵌套的`UnsatisfiedDependencyException`,通常是因为A依赖B,B依赖C,而C无法正确创建。 ### 解决方案 #### 1. 检查XML配置文件(针对传统Spring项目) - **属性名匹配**:确保XML中`<property name="xxx">`的`name`值与Java类中的字段名完全一致(包括大小写)[^1]。 ```xml <!-- 正确示例 --> <bean id="userService" class="com.example.UserService"> <property name="userDao" ref="userDao"/> <!-- 确保UserService类中有userDao字段 --> </bean> ``` - **bean引用存在性**:检查所有`ref`引用的bean是否已定义。 #### 2. 解决类未找到问题(JAR包运行) - **检查依赖完整性**: - 使用Maven:执行`mvn dependency:tree`查看依赖树,排除冲突或缺失的依赖。 - 确保打包时包含所有依赖(如使用`maven-assembly-plugin`)。 - **类路径扫描配置**: - 在Spring Boot中检查`@ComponentScan`是否覆盖了所有需要扫描的包[^2]: ```java @SpringBootApplication @ComponentScan(basePackages = {"com.example", "com.another.package"}) // 显式指定扫描包 public class Application {...} ``` #### 3. 解决循环依赖 - **使用setter注入代替构造器注入**: ```java @Service public class ServiceA { private ServiceB serviceB; @Autowired // 通过setter注入打破循环 public void setServiceB(ServiceB serviceB) { this.serviceB = serviceB; } } ``` - **使用`@Lazy`延迟加载**: ```java @Service public class ServiceA { @Autowired @Lazy // 延迟初始化ServiceB private ServiceB serviceB; } ``` #### 4. 检查依赖注入方式 - **字段注入问题**:如果使用`@Autowired`进行字段注入,确保类已被Spring管理(如添加`@Service`等注解)。 - **构造器注入**:Spring 4.3+支持单构造器的隐式注入,但若有多个构造器需用`@Autowired`指定。 #### 5. 日志分析 - **查看完整堆栈**:从日志末尾的`Caused by`开始向上排查根本原因(如引用[3]的日志显示`topicService`→`userService`→`storeOrderService`的依赖链问题)。 - **启用调试日志**:在`application.properties`中添加: ```properties logging.level.org.springframework.beans=DEBUG ``` ### 总结步骤 1. **检查XML配置**(若使用):核对所有属性名和bean引用。 2. **确保类路径正确**:检查打包结果和组件扫描范围。 3. **解决循环依赖**:调整注入方式或使用`@Lazy`。 4. **分析依赖链**:通过日志定位具体失败的bean创建位置。 > 关键提示:多层嵌套的`UnsatisfiedDependencyException`通常指向依赖链末端的bean创建失败,需从最内层的`Caused by`开始解决[^3]。 §§相关问题§§ 1. 如何解决 Spring 项目打包成 JAR 后出现的 `ClassNotFoundException`? 2. 在 Spring 中如何正确使用 `@ComponentScan` 注解? 3. 如何通过日志分析 Spring 依赖注入失败的原因? 4. Spring 中构造器注入和 setter 注入有哪些区别? 5. 如何检测和解决 Spring 中的循环依赖问题?</think>### Spring `UnsatisfiedDependencyException` 错误详解与解决方案 `UnsatisfiedDependencyException` 是 Spring 框架运行时常见的依赖注入失败错误,表示 Spring 容器无法满足某个 bean 的依赖关系。以下是系统化的原因分析和解决方案: --- #### 一、核心原因分析 1. **XML 配置错误**(最常见)[^1] - 属性名与字段名大小写不一致 - 依赖的 bean 未在 XML 中定义 - 配置文件路径错误或未加载 2. **类路径问题** [^2] - 依赖的类未编译到 `target/classes` - JAR 包中缺少必要的类文件 - 包扫描范围未覆盖需要的组件 3. **循环依赖** [^3] ```java // 典型循环依赖场景 @Service public class ServiceA { @Autowired private ServiceB serviceB; // ← 依赖ServiceB } @Service public class ServiceB { @Autowired private ServiceA serviceA; // ← 又依赖ServiceA } ``` 4. **版本冲突** - Spring Boot 与 Spring Cloud 版本不兼容 - 第三方库存在多个冲突版本 --- #### 二、系统化解决方案 ##### 1. 修复 XML 配置(传统 Spring 项目) ```xml <!-- 正确配置示例 --> <bean id="userService" class="com.example.UserService"> <!-- 确保name值与Java字段名完全一致 --> <property name="userDao" ref="userDao"/> </bean> <bean id="userDao" class="com.example.UserDaoImpl"/> ``` - 检查点: - 所有 `ref` 引用的 bean 必须存在定义 - 属性名严格匹配字段名(包括大小写) - 确认 `web.xml` 已加载配置文件 [^1] ##### 2. 解决类路径问题 ```java @SpringBootApplication // 显式添加需要扫描的包路径 @ComponentScan(basePackages = {"com.example", "org.thirdparty"}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` - 验证步骤: 1. 检查 `target/classes` 目录是否包含 bean 类 2. 执行 `mvn dependency:tree` 检查依赖冲突 3. 打包时确保包含所有依赖(使用 `maven-assembly-plugin`) ##### 3. 打破循环依赖 ```java @Service public class ServiceA { @Autowired @Lazy // 延迟加载解决循环依赖 private ServiceB serviceB; } ``` 替代方案: - 使用 setter 注入代替字段注入 - 重构代码提取公共功能到第三个服务 ##### 4. 版本冲突解决方案 ```xml <!-- pom.xml 中锁定版本 --> <properties> <spring-boot.version>2.7.3</spring-boot.version> <spring-cloud.version>2021.0.3</spring-cloud.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> ``` --- #### 三、调试技巧 1. **日志分析重点** [^3] ```log Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.StoreOrderService' available ``` - 从最内层的 `Caused by` 开始排查 2. **启用详细日志** ```properties # application.properties logging.level.org.springframework.beans=DEBUG logging.level.org.springframework.context=DEBUG ``` 3. **运行时检查** ```java // 在启动类打印所有注册的Bean public static void main(String[] args) { ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args); Arrays.stream(ctx.getBeanDefinitionNames()).forEach(System.out::println); } ``` --- > **关键提示**:超过 70% 的 `UnsatisfiedDependencyException` 由配置错误引起。从异常堆栈的最内层 `Caused by` 开始排查,重点关注未找到的 bean 类型或类名[^1][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值