循环依赖

循环依赖其实就是循环引用,也就是两个或则两个以上的bean互相持有对方,最终形成闭环。比如A依赖于B,B依赖于C,C又依赖于A。如下图:

Spring 循环依赖 

这里不是函数的循环调用,是对象的相互依赖关系。循环调用其实就是一个死循环,最终会导致内存溢出错误,除非有终结条件。

依赖配置 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    <!--<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">-->

        <!--<property name="locations">-->
            <!--<list>-->
                <!--<value>classpath*:/resous.properties</value>-->
            <!--</list>-->
        <!--</property>-->
    <!--</bean>-->

    <bean id="schoolA" class="com.fyp.spring.source.beans.SchoolA">
        <property name="name" value="张三"></property>
        <property name="daynatic" value="test"></property>
        <property name="students" ref="studentB"></property>
    </bean>

    <bean id="studentB" class="com.fyp.spring.source.beans.StudentsB">
        <property name="name" value="张三"></property>
        <property name="age" value="30"></property>
        <property name="school" ref="schoolA"></property>
    </bean>

</beans>
Spring.xml

相关文章: