Spring中的循环依赖 [英] Circular dependency in Spring

查看:112
本文介绍了Spring中的循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring如何解决这个问题:bean A依赖于bean B,bean A依赖于bean A.

How does Spring resolve this: bean A is dependent on bean B, and bean B on bean A.

推荐答案

As其他答案说,Spring只是处理它,创建bean并根据需要注入它们。

As the other answers have said, Spring just takes care of it, creating the beans and injecting them as required.

其中一个后果是可能发生bean注入/属性设置以与XML布线文件似乎暗示的顺序不同的顺序排列。因此,您需要注意,您的属性设置器不会执行依赖于已调用的其他setter的初始化。处理此问题的方法是将bean声明为实现 InitializingBean 接口。这要求您实现 afterPropertiesSet()方法,这是您进行关键初始化的地方。 (我还包括用于检查实际已设置重要属性的代码。)

One of the consequences is that bean injection / property setting might occur in a different order to what your XML wiring files would seem to imply. So you need to be careful that your property setters don't do initialization that relies on other setters already having been called. The way to deal with this is to declare beans as implementing the InitializingBean interface. This requires you to implement the afterPropertiesSet() method, and this is where you do the critical initialization. (I also include code to check that important properties have actually been set.)

这篇关于Spring中的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆