How does Spring framework autowire a collection

↘锁芯ラ 提交于 2020-01-23 07:14:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!