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

后端 未结 2 1668
情歌与酒
情歌与酒 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 19:01

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

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

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

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

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

提交回复
热议问题