Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

spring

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

No matching bean of type [SomeBeanClass] found for dependency [collection of SomeBeanClass]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

If I add (required=false), I get null for beans. But it looks like error prone solution requiring null checks.

Is there an easy way (one liner) to autowire empty collection if no beans present?

like image 783
Timofey Gorshkov Avatar asked Oct 10 '13 14:10

Timofey Gorshkov


People also ask

Can we use @autowired without @component?

So the answer is: No, @Autowired does not necessarily mean you must also use @Component . It may be registered with applicationContext. xml or @Configuration+@Bean .

What can I use instead of Autowired?

You can indicate a @Primary candidate for @Autowired. This sets a default class to be wired. Some other alternatives are to use @Resource, @Qualifier or @Inject.

Can we use @autowire without using Spring boot context?

Sure you can use @Autowired but as your JobMain isn't a a Spring bean it will ofcourse not be autowired. Basically that is duplicate of this (more reasons here. So to fix make your JobMain an @Component and don't construct a new instance yourself.

What is difference between @bean and @autowire?

@Bean is just for the metadata definition to create the bean(equivalent to tag). @Autowired is to inject the dependancy into a bean(equivalent to ref XML tag/attribute).


1 Answers

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.

like image 172
Benjamin M Avatar answered Sep 24 '22 19:09

Benjamin M