Inject a list of beans using Spring @Configuration annotation

前端 未结 1 578
梦如初夏
梦如初夏 2021-02-09 01:16

I\'ve got a Spring bean, and in the Spring Bean I have a dependency on a list of other beans. My question is: how can I inject a Generic list of beans as a dependency of that be

相关标签:
1条回答
  • 2021-02-09 01:39

    What you have should work, having a @Resource or @Autowired on the setter should inject all instances of Color to your List<Color> field.

    If you want to be more explicit, you can return a collection as another bean:

    @Bean
    public List<Color> colorList(){
        List<Color> aList = new ArrayList<>();
        aList.add(blue());
        return aList;
    }     
    

    and use it as an autowired field this way:

    @Resource(name="colorList") 
    public void setColors(List<Color> colors) {
        this.colors = colors;
    }
    

    OR

    @Resource(name="colorList")
    private List<Color> colors;
    

    On your question about returning an interface or an implementation, either one should work, but interface should be preferred.

    0 讨论(0)
提交回复
热议问题