public class ClassA { private ClassB classB; public ClassB getClassB() { return classB; } public void setClassB(ClassB classB) { this.classB = classB; } } public class ClassB { private ClassA classA; public ClassA getClassA() { return classA; } public void setClassA(ClassA classA) { this.classA = classA; } }
<?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.xsd"> <bean id="classA" class="ioc.cd.ClassA"> <property name="classB" ref="classB"></property> </bean> <bean id="classB" class="ioc.cd.ClassB"> <property name="classA" ref="classA"></property> </bean> </beans>
@Test public void test() throws Exception { // 创建IoC容器,并进行初始化 String resource = "spring/spring-ioc-circular-dependency.xml"; ApplicationContext context = new ClassPathXmlApplicationContext(resource); // 获取ClassA的实例(此时会发生循环依赖) ClassA classA = (ClassA) context.getBean(ClassA.class); }