Is there an easy way to autowire empty collection if no beans present in Spring?
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.
If I add
(required=false)
, I getnull
forbeans
.
Does the field get explicitly set to null or does it simply not get set at all? Try adding an initializer expression
@Autowired(required=false) List<SomeBeanClass> beans = new ArrayList<>();