Reputation: 1331
I want to inject a list of beans into a spring bean with constructor injection.
@Component
public void MyBean {
@Autowired
public MyBean(List<BeanToInject> beanList) {
...
}
}
But the implementations of the BeanToInject are in other modules. These modules might be turned off. If there is no implementation of BeanToInject in the applicationcontext, the spring throws an exception on start instead of injecting an empty list. What can I do? (Setter and private property based autowiring is not an option for me.)
Upvotes: 5
Views: 1975
Reputation: 695
In Spring, Autowired can have a required value to define it requires or not when autowire. But this cannot apply to constructor. In your case, the best solution is using autowired in method or properties and apply
@Autowired(required=false)
private List<BeanToInject> beanList;
Or
@Autowired(required=false)
public void setBeanList(List<BeanToInject> beanList);
Upvotes: 2
Reputation: 44535
If you use Java 8, you can use Optional:
@Autowired
public TestComponent(Optional<List<BeanToInject>> beanList) {
if (beanList.isPresent()) {
// There are beans in the list
} else {
// No beans injected
}
}
Upvotes: 1