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?
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 .
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.
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.
@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).
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With