按类型将引用bean自动装配到列表中 [英] Autowire reference beans into list by type
问题描述
我有一个类,其中包含守护程序
类型的对象列表。
I have one class that has a list of objects of Daemon
type.
class Xyz {
List<Daemon> daemons;
}
我的弹簧配置如下所示。
My spring configuration looks like this.
<bean id="xyz" class="package1.Xyz">
<property name="daemons" ref="daemonsList">
</bean>
<bean id="daemon1" class="package1.DaemonImpl1"/>
<bean id="daemon2" class="package1.DaemonImpl2"/>
<bean id="daemonsList" class="java.util.ArrayList">
<constructor-arg>
<list>
<ref bean="daemon1" />
<ref bean="daemon2" />
</list>
</constructor-arg>
</bean>
现在不是在列表中显式连接每个守护进程实现,而是可以自动装配所有类型的bean 守护程序
自动列在列表中。我试图解决的问题是,如果有人创建了一个新的守护程序
类实现的bean,并忘记将其连接到列表中。
Now instead of explicitly wiring each daemon implementation in list, is it possible to autowire all beans of type Daemon
automatically in list. Problem I am trying to solve is, If someone creates a bean of new implementation of Daemon
class and forgets to wire it into list.
我在stackoverflow上的某个地方看到过这个问题,但是无法再找到它。为它道歉。
I have seen this question somewhere on stackoverflow but not able to find that again. Apologies for it.
推荐答案
它应该像这样工作(从你的XML中删除ArrayList bean):
It should work like this (remove the ArrayList bean from your XML):
public Class Xyz {
private List<Daemon> daemons;
@Autowired
public void setDaemons(List<Daemon> daemons){
this.daemons = daemons;
}
}
我认为没有在XML中执行此操作的方法。
I don't think there's a way to do this in XML.
请参阅:
3.9.2。 @Autowired
和 @Inject
:
See:
3.9.2. @Autowired
and @Inject
:
还可以通过将注释添加到
期望该类型数组的字段或方法中,从
ApplicationContext提供特定类型的所有bean:
It is also possible to provide all beans of a particular type from the ApplicationContext by adding the annotation to a field or method that expects an array of that type:
public class MovieRecommender {
@Autowired
private MovieCatalog[] movieCatalogs;
// ...
}
同样适用于类型化集合:
The same applies for typed collections:
public class MovieRecommender {
private Set<MovieCatalog> movieCatalogs;
@Autowired
// or if you don't want a setter, annotate the field
public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {
this.movieCatalogs = movieCatalogs;
}
// ...
}
BTW,从Spring 4.x开始,可以使用 @Ordered
机制自动订购这些列表。
BTW, as of Spring 4.x, these lists can be ordered automatically using the @Ordered
mechanism.
这篇关于按类型将引用bean自动装配到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!