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.

Leave a Comment

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)