原创

Is there an unresolvable circular reference循环注入问题的解决

今天在在项目中新增了一个服务,然后启动该服务,spring容器初始化报错:循环依赖,错误信息如下:
Requested bean is currently in creation: Is there an unresolvable circular reference?
折腾了三个小时,特此记录一下! 错误的原因大概是: 新增该服务之前,服务A已经注入了服务C中的bean,现在新增的服务B也要注入服务C中的同一个bean。此时服务A已经启动,如果再启动服务B,就会报错了。
org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'resourceServerConfig': Unsatisfied dependency expressed through field 'tokenStore'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'authorizationServerConfig': Unsatisfied dependency expressed through field 'tokenStore'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'tokenStore': Requested bean is currently in creation: Is there an unresolvable circular reference?
 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:660) ~[spring-beans-5.3.9.jar!/:5.3.9]
 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.9.jar!/:5.3.9]
 at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.9.jar!/:5.3.9]
 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.9.jar!/:5.3.9]

问题解决:Spring中的 @Lazy注解 11   @Lazy注解注解的作用主要是减少springIOC容器启动的加载时间。 Spring IoC (ApplicationContext) 容器一般都会在启动的时候实例化所有单实例 bean 。如果我们想要 Spring 在启动的时候延迟加载 bean,即在调用某个 bean 的时候再去初始化,那么就可以使用 @Lazy 注解。当出现循环依赖时,也可以添加@Lazy 总结:回过头想想,这个问题的发生原因和解决方法都十分简单,耽误了这么多时间,主要还是因为不熟悉spring的机制和相关注解,之前也用过@Lazy这个注解,但是都是直接照搬过来了,没有深究其中的意义,导致真正的问题出现时,脑海中想不到此方法。 希望我踩过的坑,能帮助路过的其他人,解决这个问题吧~
正文到此结束
Loading...