user1552545
user1552545

Reputation: 1331

Spring nonrequired properties in constructor?

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

Answers (2)

Tan Mai Van
Tan Mai Van

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

dunni
dunni

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

Related Questions