我有 3 个项目:
- 框架
- 产品a
- 产品-b
每个产品都依赖于框架,但它们彼此不了解。
我有 3 个 spring 配置文件:每个项目一个。每个产品的配置文件包括(带<import resource="classpath:/...
)框架的配置文件。
在框架中有一个叫做“manager”的bean,它有一个属性List<AnInterface> theList
。 . “管理器”有一个 addXxx(anImplementation),它将元素添加到列表中。
框架和每个产品都提供了 AnInterface
的实现, 必须添加到 theList
.
所以最后,当 product-a 运行时,管理器包含来自框架和来自 product-a 的实现,与 product-b 相同
使用 Spring 执行此初始化的最佳做法是什么?
我能想到的唯一解决方案是创建一个专用类,构造函数将获取管理器和贡献列表,并将它们添加到管理器,但它很难看,因为 1/它在构造函数中操作外部对象,2/我必须创建一个虚拟类来初始化其他类...我不喜欢这样。
最佳答案
我认为如果不是真的需要,代码不应该知道 Spring。因此我会在 Spring 配置中进行所有初始化。
我们可以使用bean definition inheritance和属性压倒一切。
框架类
public class Manager {
private List<AnInterface> theList;
public void init() {
// here we use list initialized by product
}
}
框架上下文
<bean id="manager"
init-method="init"
abstract="true"
class="Manager">
<property name="theList">
<list/> <!-- this will be overriden or extnded -->
</property>
</bean>
产品 A 背景
<bean id="managerA"
parent="manager"
scope="singleton"
lazy-init="false">
<property name="theList">
<list>
<ref bean="impl1"/>
<ref bean="impl2"/>
</list>
</property>
</bean>
注意此类配置中的父属性和子属性。并不是所有的都是从 parent 那里继承来的。 Spring 文档指定:
The remaining settings are always taken from the child definition: depends on, autowire mode, dependency check, singleton, scope, lazy init.
此外,还有collection merging在 Spring 中,通过指定子 bean
<list merge="true">
您可以合并父列表和子列表。
我在许多项目和一些基于 Spring 的可扩展 Web 框架中观察到这种模式。
关于java - 如何使用 Spring 为 bean 的列表属性做贡献?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17533601/