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

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

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

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

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

    <bean id="person" class="pojo.Person">
        <constructor-arg index="0" value="小明"/>
        <constructor-arg index="1" value="12"/>
        <constructor-arg index="2" value="student"/>
    </bean>

    <bean id="student" class="pojo.Student">
        <constructor-arg index="0" value="小王"/>
        <constructor-arg index="1" value="13"/>
        <constructor-arg index="2" value="person"/>
    </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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值