服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - JAVA教程 - 浅谈Spring解决循环依赖的三种方式

浅谈Spring解决循环依赖的三种方式

2021-02-06 12:25学习园 JAVA教程

本篇文章主要介绍了浅谈Spring循环依赖的三种方式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

引言:循环依赖就是n个类中循环嵌套引用,如果在日常开发中我们用new 对象的方式发生这种循环依赖的话程序会在运行时一直循环调用,直至内存溢出报错。下面说一下spring是如果解决循环依赖的。

第一种:构造器参数循环依赖

表示通过构造器注入构成的循环依赖,此依赖是无法解决的,只能抛出beancurrentlyin creationexception异常表示循环依赖。

如在创建testa类时,构造器需要testb类,那将去创建testb,在创建testb类时又发现需要testc类,则又去创建testc,最终在创建testc时发现又需要testa,从而形成一个环,没办法创建。

spring容器会将每一个正在创建的bean 标识符放在一个“当前创建bean池”中,bean标识符在创建过程中将一直保持
在这个池中,因此如果在创建bean过程中发现自己已经在“当前创建bean池”里时将抛出
beancurrentlyincreationexception异常表示循环依赖;而对于创建完毕的bean将从“当前创建bean池”中清除掉。

首先我们先初始化三个bean。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class studenta {
 
 private studentb studentb ;
 
 public void setstudentb(studentb studentb) {
 this.studentb = studentb;
 }
 
 public studenta() {
 }
 
 public studenta(studentb studentb) {
 this.studentb = studentb;
 }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class studentb {
 
 private studentc studentc ;
 
 public void setstudentc(studentc studentc) {
 this.studentc = studentc;
 }
 
 public studentb() {
 }
 
 public studentb(studentc studentc) {
 this.studentc = studentc;
 }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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管理,并用有参构造实例化

?
1
2
3
4
5
6
7
8
9
<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>

下面是测试类:

?
1
2
3
4
5
6
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解决循环依赖的三种方式

如图中前两步骤得知:spring是先将bean对象实例化之后再设置对象属性的

修改配置文件为set方式注入

?
1
2
3
4
5
6
7
8
9
10
<!--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>

下面是测试类:

?
1
2
3
4
5
6
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类中

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/** 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

对于"prototype"作用域bean,spring容器无法完成依赖注入,因为spring容器不进行缓存"prototype"作用域的bean,因此无法提前暴露一个创建中的bean。

修改配置文件为:

?
1
2
3
4
5
6
7
8
9
<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单例作用域。

测试用例:

?
1
2
3
4
5
6
7
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。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/u010644448/article/details/59108799

延伸 · 阅读

精彩推荐
  • JAVA教程基于Spring + Spring MVC + Mybatis 高性能web构建实例详解

    基于Spring + Spring MVC + Mybatis 高性能web构建实例详解

    这篇文章主要介绍了基于Spring + Spring MVC + Mybatis 高性能web构建实例详解,需要的朋友可以参考下...

    梦想合伙人2262020-09-12
  • JAVA教程java之super关键字用法实例解析

    java之super关键字用法实例解析

    这篇文章主要介绍了java之super关键字用法实例解析,较为详细的分析了super关键字的用法及内存分布,需要的朋友可以参考下 ...

    shichen20143932019-12-01
  • JAVA教程springAOP的三种实现方式示例代码

    springAOP的三种实现方式示例代码

    这篇文章主要介绍了springAOP的三种实现方式,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考...

    易水寒的博客2522020-07-21
  • JAVA教程25个最好的免费Eclipse插件

    25个最好的免费Eclipse插件

    这篇文章为大家分享了25个让Java程序员更高效的Eclipse插件,感兴趣的朋友可以参考一下 ...

    Sunshine_lily5952020-03-10
  • JAVA教程java计算集合对称差的示例代码

    java计算集合对称差的示例代码

    本篇文章主要介绍了java计算集合对称差的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    xixicat4302020-12-24
  • JAVA教程Java 正则表达式详细介绍

    Java 正则表达式详细介绍

    本文主要介绍 Java 正则表达式的内容,这里整理了Java 正则表达式的相关资料,并详细介绍,附有代码示例,有兴趣的小伙伴可以参考下...

    kdnuggets1992020-06-10
  • JAVA教程java微信公众号开发案例

    java微信公众号开发案例

    这篇文章主要为大家详细介绍了java微信公众号开发案例,如何接入公众号,订阅号怎么样接收消息,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    伟雪无痕3862020-07-06
  • JAVA教程详解Java中@Override的作用

    详解Java中@Override的作用

    这篇文章主要介绍了详解Java中@Override的作用的相关资料,希望通过本文能帮助到大家,让大家理解这部分内容,需要的朋友可以参考下...

    _QING_FENG5972021-01-19