Is there an easy way to autowire empty collection if no beans present in Spring?

后端 未结 2 1655
情歌与酒
情歌与酒 2021-01-03 18:38

If I have @Autowired List beans; and no beans of SomeBeanClass, I get:

No matching bean of type [SomeBe

相关标签:
2条回答
  • 2021-01-03 18:52

    If I add (required=false), I get null for beans.

    Does the field get explicitly set to null or does it simply not get set at all? Try adding an initializer expression

    @Autowired List<SomeBeanClass> beans = new ArrayList<>();
    
    0 讨论(0)
  • 2021-01-03 19:01

    There are a few options with Spring 4 and Java 8:

    @Autowired(required=false)
    private List<Foo> providers = new ArrayList<>();
    

    You can also use java.util.Optional with a constructor:

    @Autowired
    public MyClass(Optional<List<Foo>> opFoo) {
        this.foo = opFoo.orElseGet(ArrayList::new);
    }
    

    You should also be able to autowire an a field with Optional<List<Foo>> opFoo;, but I haven't used that yet.

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