Spring 通过构造方法注入导致的循环依赖问题

如果你主要使用构造函数注入,则可以创建无法解析的循环依赖关系场景。

例如:类A通过构造函数注入需要类B的实例,而类B通过构造函数注入需要类A的实例。如果将A类和B类的bean配置为相互注入,则Spring IoC容器会在运行时检测此循环引用,并抛出a BeanCurrentlyInCreationException

一种可能的解决方案是编辑由setter而不是构造函数配置的某些类的源代码。或者,避免构造函数注入并仅使用setter注入。换句话说,尽管不推荐使用,但您可以使用setter注入配置循环依赖关系。

与典型情况(没有循环依赖)不同,bean A和bean B之间的循环依赖强制其中一个bean在完全初始化之前被注入另一个bean(经典的鸡与鸡蛋场景)。

    
        
        
        
    

    
        
        
        
    

十一月 08, 2018 11:15:52 下午 org.springframework.context.support.GenericApplicationContext refresh
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'person' defined in class path resource [applicationContext.xml]: Unsatisfied dependency expressed through constructor parameter 2: Could not convert argument value of type [java.lang.String] to required type [pojo.Student]: Failed to convert value of type 'java.lang.String' to required type 'pojo.Student'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'pojo.Student': no matching editors or conversion strategy found
十一月 08, 2018 11:15:52 下午 org.springframework.test.context.TestContextManager prepareTestInstance
严重: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@6fb554cc] to prepare test instance [demo.Demo1@55ca8de8]
java.lang.IllegalStateException: Failed to load ApplicationContext

你可能感兴趣的:(开发中遇到的问题)