简体   繁体   English

如何在 spring 引导中注入自定义 bean 列表

[英]How to inject custom list of beans in spring boot

Assume that all BarX are children of Foo type.假设所有BarX都是Foo类型的孩子。

My bean configuration class is:我的 bean 配置 class 是:

class MyConfig{
    @Bean
    public Foo barA() {
        return new BarA();
    }

    @Bean
    public Foo barB() {
        return new BarB();
    }

    @Bean
    public Foo barC() {
        return new BarC();
    }

    @Bean
    public List<Foo> getDefaultFoos(BarA barA, BarB barB) {
        return List.of(barA, barB);
    }

    @Bean
    public OtherType other(List<Foo> defaultFoos, ApplicationContext applicationContext) {
        return new OtherType(defaultFoos, applicationContext); 
        /* Expecting `List<Foo> defaultFoos` from method `getDefaultFoos` which is [barA, barB] 
        but getting list of all Bars which is [barA, barB, barC]
        */
    }
}

In method OtherType other ,在方法OtherType other中,

Expecting List<Foo> defaultFoos from method getDefaultFoos which is [barA, barB] only but getting list of all Bars which is [barA, barB, barC]期望来自方法getDefaultFoosList<Foo> defaultFoos仅为[barA, barB]但获取所有 Bars 的列表[barA, barB, barC]

How to inject a custom list Foo instead of all of it in 'other' bean?如何在“其他”bean中注入自定义列表Foo而不是全部?

Use @Qualifier to specify the exact bean you need.使用@Qualifier指定您需要的确切 bean。

@Bean
public OtherType other(@Qualifier("getDefaultFoos") List<Foo> defaultFoos, ApplicationContext applicationContext) {
  return new OtherType(defaultFoos, applicationContext);
}

When you autowire a list of something, the default behaviour is to get every bean matching, which you are seeing here.当您自动装配某些内容的列表时,默认行为是获取每个 bean 匹配,您在此处看到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM