Spring 框架如何自动装配一个集合

How does Spring framework autowire a collection

我从未见过自动装配的集合:

@Service
public class SomeFactory {
    @Autowired
    private List<Foo> foos;

    @PostConstruct
    public void init() {
        for(Foo foo: foos) { 
            //do something
        }
    }
}

在 init() 方法中,我可以看到 foos 已经有几个条目。我想 Spring 知道谁应该是 foos 的入口。但是,怎么办?想在foos中添加一个Foo对象怎么办?需要在 属性 文件中配置,或任何其他想法?

Spring 的 BeanFactory 基本上是 bean 的注册表。这些 bean 可以使用 XML 声明,或者使用配置 class 中的 @Bean 注释方法,或者使用包扫描自动发现。

当您请求 List<Foo> 时,Spring 找到所有类型为 Foo 的 bean,创建一个包含这些 bean 的列表,然后注入该列表。

documentation about Autowired 对此进行了解释,顺便说一句:

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

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?

创建应用程序上下文/Bean 工厂时,默认情况下(如果没有另外指定惰性 init 或非单例范围),也会创建所有 beans。 应用上下文知道这些 bean。因此,当我们尝试 @Autowire 特定类型 bean 的集合时,例如 private List<Foo> foos;,Spring 找到所有 foos,将它们添加到列表中并注入依赖 bean。

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?

有多种方法可以做到这一点。可以根据需要选择一个合适的选项。

  • 在 bean 配置 XML 文件 中声明 bean。灵活的。但你可能不喜欢在 XML.
  • 中这样做
  • @Component bean 上的注释 class。 class 将由 Spring 扫描并配置组件扫描。没有 XML 但不太灵活。 Bean class 定义和声明是紧耦合的。无法在不同的 Application Context.
  • 中创建 @Component bean
  • @Bean 方法上的注释 returns @Configuration 中的 bean 注释 class 。最好的。 Bean class 定义和声明是解耦的,仅通过注解完成。我们也可以从另一个 Application Context 中的方法创建 @Bean 带注释的 bean。