java - spring容器如何解决循环依赖
问题描述
例如 Employee 类依赖于 Student 类,Student 类依赖于 Person 类,Person 类依赖于 Employee 类
解决方案
首先:尽可能避免循环依赖。
这促进了类之间的高度耦合,并使整个设计更加复杂。
这与没有 Spring 的方式相同。
使用构造函数在两个类中设置依赖关系,您会因为循环创建而陷入困境:
public Foo(Bar bar){...
}
public Bar(Foo foo){...
}
Bar bar = new Bar(new Foo(???)); // stuck
Foo foo = new Foo(new Bar(???)); // stuck
在一侧使用构造函数,在另一侧使用设置器,您可以缓解创建问题:
Foo类:
public Foo(){...
}
public setBar(Bar bar){...
}
酒吧类:
public Bar(Foo foo){...
}
你可以这样做:
Foo foo = new Foo(); // ok
Bar bar = new Bar(foo); // ok
foo.setBar(bar); // ok
具体来说,在 Spring 中,如果在两个类中都使用构造函数注入,则 Spring 容器启动将失败,因为这需要使用不存在的 bean 作为 arg 实例化类(通过反射)。
如果您不同时使用构造函数注入,而是使用 setter 或字段注入,Spring 将通过分两步做事来缓解这种情况:
- instantiate the beans with the no arg constructor
- set dependency foo in bar
- set dependency bar in foo
推荐阅读
- variables - Netlogo:将补丁变量值设置为相邻补丁变量值
- .htaccess - 使用 .htaccess 从 domain.com/project/public 删除 /public
- apache-nifi - 判断一个数组是否有元素,Nifi
- unity3d - 我正在统一开发一个项目,它说“无法加载关联的脚本,请修复任何编译错误并分配一个有效的脚本”
- react-redux - 无法使用 @reduxjs/toolkit 发送操作 onclick 撰写按钮,它显示“TypeError (0 , _mailSlice.openComposeModal) 不是函数”
- javascript - 如果 classname === id 则删除一个类
- python - 如果我的列表中的元素正在增加,哪种计算方法是最快的?
- python - 两个数据框之间的匹配并将结果添加到其中一个的列(熊猫)
- c++ - 如何处理谓词/比较器/函子失效?
- azure - 如何创建用于将 Azure 容器组部署到 ACI 的 GitHub 工作流?