Spring循环依赖的三种方式(推荐)
引言:循环依赖就是n个类中循环嵌套引用,如果在日常开发中我们用new 对象的方式发生这种循环依赖的话程序会在运行时一直循环调用,直至内存溢出报错。下面说一下spring是如果解决循环依赖的。
第一种:构造器参数循环依赖
spring容器会将每一个正在创建的bean 标识符放在一个“当前创建bean池”中,bean标识符在创建过程中将一直保持
在这个池中,因此如果在创建bean过程中发现自己已经在“当前创建bean池”里时将抛出
beancurrentlyincreationexception异常表示循环依赖;而对于创建完毕的bean将从“当前创建bean池”中清除掉。
首先我们先初始化三个bean。
public class studenta { private studentb studentb ; public void setstudentb(studentb studentb) { this.studentb = studentb; } public studenta() { } public studenta(studentb studentb) { this.studentb = studentb; } }
public class studentb { private studentc studentc ; public void setstudentc(studentc studentc) { this.studentc = studentc; } public studentb() { } public studentb(studentc studentc) { this.studentc = studentc; } }
public class studentc { private studenta studenta ; public void setstudenta(studenta studenta) { this.studenta = studenta; } public studentc() { } public studentc(studenta studenta) { this.studenta = studenta; } }
ok,上面是很基本的3个类,,studenta有参构造是studentb。studentb的有参构造是studentc,studentc的有参构造是studenta ,这样就产生了一个循环依赖的情况,
我们都把这三个bean交给spring管理,并用有参构造实例化
<bean id="a" class="com.zfx.student.studenta"> <constructor-arg index="0" ref="b"></constructor-arg> </bean> <bean id="b" class="com.zfx.student.studentb"> <constructor-arg index="0" ref="c"></constructor-arg> </bean> <bean id="c" class="com.zfx.student.studentc"> <constructor-arg index="0" ref="a"></constructor-arg> </bean>
下面是测试类:
public class test { public static void main(string[] args) { applicationcontext context = new classpathxmlapplicationcontext("com/zfx/student/applicationcontext.xml"); //system.out.println(context.getbean("a", studenta.class)); } }
执行结果报错信息为:
caused by: org.springframework.beans.factory.beancurrentlyincreationexception:
error creating bean with name 'a': requested bean is currently in creation: is there an unresolvable circular reference?
如果大家理解开头那句话的话,这个报错应该不惊讶,spring容器先创建单例studenta,studenta依赖studentb,然后将a放在“当前创建bean池”中,此时创建studentb,studentb依赖studentc ,然后将b放在“当前创建bean池”中,此时创建studentc,studentc又依赖studenta, 但是,此时student已经在池中,所以会报错,,因为在池中的bean都是未初始化完的,所以会依赖错误 ,(初始化完的bean会从池中移除)
第二种:setter方式单例,默认方式
如果要说setter方式注入的话,我们最好先看一张spring中bean实例化的图
如图中前两步骤得知:spring是先将bean对象实例化之后再设置对象属性的
修改配置文件为set方式注入:
<!--scope="singleton"(默认就是单例方式) --> <bean id="a" class="com.zfx.student.studenta" scope="singleton"> <property name="studentb" ref="b"></property> </bean> <bean id="b" class="com.zfx.student.studentb" scope="singleton"> <property name="studentc" ref="c"></property> </bean> <bean id="c" class="com.zfx.student.studentc" scope="singleton"> <property name="studenta" ref="a"></property> </bean>
下面是测试类:
public class test { public static void main(string[] args) { applicationcontext context = new classpathxmlapplicationcontext("com/zfx/student/applicationcontext.xml"); system.out.println(context.getbean("a", studenta.class)); } }
打印结果为:
com.zfx.student.studenta@1fbfd6
为什么用set方式就不报错了呢 ?
我们结合上面那张图看,spring先是用构造实例化bean对象 ,此时spring会将这个实例化结束的对象放到一个map中,并且spring提供了获取这个未设置属性的实例化对象引用的方法。 结合我们的实例来看,,当spring实例化了studenta、studentb、studentc后,紧接着会去设置对象的属性,此时studenta依赖studentb,就会去map中取出存在里面的单例studentb对象,以此类推,不会出来循环的问题喽、
下面是spring源码中的实现方法,。以下的源码在spring的bean包中的defaultsingletonbeanregistry.java类中
/** cache of singleton objects: bean name --> bean instance(缓存单例实例化对象的map集合) */ private final map<string, object> singletonobjects = new concurrenthashmap<string, object>(64); /** cache of singleton factories: bean name --> objectfactory(单例的工厂bean缓存集合) */ private final map<string, objectfactory> singletonfactories = new hashmap<string, objectfactory>(16); /** cache of early singleton objects: bean name --> bean instance(早期的单身对象缓存集合) */ private final map<string, object> earlysingletonobjects = new hashmap<string, object>(16); /** set of registered singletons, containing the bean names in registration order(单例的实例化对象名称集合) */ private final set<string> registeredsingletons = new linkedhashset<string>(64); /** * 添加单例实例 * 解决循环引用的问题 * add the given singleton factory for building the specified singleton * if necessary. * <p>to be called for eager registration of singletons, e.g. to be able to * resolve circular references. * @param beanname the name of the bean * @param singletonfactory the factory for the singleton object */ protected void addsingletonfactory(string beanname, objectfactory singletonfactory) { assert.notnull(singletonfactory, "singleton factory must not be null"); synchronized (this.singletonobjects) { if (!this.singletonobjects.containskey(beanname)) { this.singletonfactories.put(beanname, singletonfactory); this.earlysingletonobjects.remove(beanname); this.registeredsingletons.add(beanname); } } }
第三种:setter方式原型,prototype
修改配置文件为:
<bean id="a" class="com.zfx.student.studenta" <span style="color:#ff0000;">scope="prototype"</span>> <property name="studentb" ref="b"></property> </bean> <bean id="b" class="com.zfx.student.studentb" <span style="color:#ff0000;">scope="prototype"</span>> <property name="studentc" ref="c"></property> </bean> <bean id="c" class="com.zfx.student.studentc" <span style="color:#ff0000;">scope="prototype"</span>> <property name="studenta" ref="a"></property> </bean>
scope="prototype" 意思是 每次请求都会创建一个实例对象。两者的区别是:有状态的bean都使用prototype作用域,无状态的一般都使用singleton单例作用域。
测试用例:
public class test { public static void main(string[] args) { applicationcontext context = new classpathxmlapplicationcontext("com/zfx/student/applicationcontext.xml"); <strong>//此时必须要获取spring管理的实例,因为现在scope="prototype" 只有请求获取的时候才会实例化对象</strong> system.out.println(context.getbean("a", studenta.class)); } }
打印结果:
caused by: org.springframework.beans.factory.beancurrentlyincreationexception: error creating bean with name 'a': requested bean is currently in creation: is there an unresolvable circular reference?
为什么原型模式就报错了呢 ?
对于“prototype”作用域bean,spring容器无法完成依赖注入,因为“prototype”作用域的bean,spring容
器不进行缓存,因此无法提前暴露一个创建中的bean。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。