Spring通过@Lazy解决构造方法形式的循环依赖问题
作者:amadeus_liu2
这篇文章主要给大家介绍了Spring如何通过@Lazy解决构造方法形式的循环依赖问题,文中有详细的代码示例,对大家的学习活工作有一定的帮助,具有一定的参考价值,需要的朋友可以参考下
一、定义2个循环依赖的类
package cn.edu.tju.domain2; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; @Component public class A { private final B b; public B getB() { return b; } @Lazy public A(B b){ this.b = b; //System.out.println(b); } }
package cn.edu.tju.domain2; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; @Component public class B { private final A a; public A getA() { return a; } @Lazy public B(A a){ this.a =a; //System.out.println(a); } }
二、定义配置文件(spring09.xml):
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="cn.edu.tju.domain2"/> </beans>
三、定义测试类:
package cn.edu.tju; import cn.edu.tju.domain.Husband; import cn.edu.tju.domain2.A; import cn.edu.tju.domain2.B; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidPooledConnection; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ConfigurationClassPostProcessor; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.sql.SQLException; public class Test09 { public static void main(String[] args) throws Exception { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("spring09.xml"); A a = ctx.getBean("a", A.class); B b = ctx.getBean("b", B.class); System.out.println(a.getClass().getName()); System.out.println(a.getB().getA() == a); System.out.println(a.getB().getClass().getName()); System.out.println(b.getA().getClass().getName()); } }
四、执行结果:
以上就是Spring通过@Lazy解决构造方法形式的循环依赖问题的详细内容,更多关于Spring @Lazy解决循环依赖的资料请关注脚本之家其它相关文章!