简体   繁体   中英

How to inject custom list of beans in spring boot

Assume that all BarX are children of Foo type.

My bean configuration class is:

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 ,

Expecting List<Foo> defaultFoos from method getDefaultFoos which is [barA, barB] only but getting list of all Bars which is [barA, barB, barC]

How to inject a custom list Foo instead of all of it in 'other' bean?

Use @Qualifier to specify the exact bean you need.

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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