问题
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
}
}
}
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?
回答1:
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.
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.
The documentation about Autowired explains it, BTW:
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
来源:https://stackoverflow.com/questions/37915039/how-does-spring-framework-autowire-a-collection