Spring框架如何自动装配集合 [英] How does Spring framework autowire a collection
问题描述
我从未见过自动收集的集合:
I've never seen an autowired collection:
@Service
public class SomeFactory {
@Autowired
private List<Foo> foos;
@PostConstruct
public void init() {
for(Foo foo: foos) {
//do something
}
}
}
在init()方法中,我可以看到foos已经有几个条目。我猜Spring知道谁应该是foos的入口。但是,怎么样?如果我想将Foo对象添加到foos中,我该怎么办?需要在属性文件中配置,还是任何其他想法?
In init() method, I can see foos has several entries already. I guess Spring knows who's supposed to be the entry of foos. But, how? What should I do if I want to add a Foo object into foos? Need to configure in a property file, or any other idea?
推荐答案
Spring的BeanFactory基本上是bean的注册表。这些bean可以使用XML声明,或者使用Configuration类中的 @Bean
-annotated方法声明,或者使用包扫描自动发现。
Spring's BeanFactory is basically a registry of beans. These beans can be declared using XML, or using @Bean
-annotated methods in a Configuration class, or be automatically discovered using package scanning.
当你要求 List< Foo>
时,Spring会找到所有类型为Foo的bean,创建一个包含这些bean的List,然后注入list。
When you ask for a List<Foo>
, Spring finds all the beans that are of type Foo, creates a List containing those beans, and injects that list.
关于Autowired的文档解释了它,BTW:
这也是可能的通过向需要该类型数组的字段或方法添加注释来提供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
这篇关于Spring框架如何自动装配集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!