Home > Enterprise >  How to inject custom list of beans in spring boot
How to inject custom list of beans in spring boot

Time:08-25

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?

CodePudding user response:

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.

  • Related