Spring 框架如何自动装配一个集合 [英] How does Spring framework autowire a collection

查看:36
本文介绍了Spring 框架如何自动装配一个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 的入口.但是,怎么样?如果我想在 foos 中添加一个 Foo 对象应该怎么做?需要在属性文件中进行配置,还是有其他想法?

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 声明,或者使用配置类中的 @Bean 注释方法,或者使用包扫描自动发现.

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 时,Spring 会找到所有 Foo 类型的 bean,创建一个包含这些 bean 的 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 的文档 解释一下,顺便说一句:

The documentation about Autowired explains it, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆