In a @Service
, I want to include two @Component
, say ComponentA
and ComponentB
.
Both of these components are conditional on some property (e.g. some environment variable; meaning these beans do not exist if those environment variables are not set).
In the service, there are other auto wired beans, which are not optional. Given that I am using constructor dependency injection, I do not want to create multiple constructors, but indicate to Spring to use null
when instantiating my service. The following works:
public MainService(NonOptionalBean1 b1, NonOptionalBean2 b2,
..., ComponentA a, ComponentB b) { ... }
public MainService(NonOptionalBean1 b1, NonOptionalBean2 b2,
..., ComponentA a) { ... }
public MainService(NonOptionalBean1 b1, NonOptionalBean2 b2,
..., ComponentB b) { ... }
public MainService(NonOptionalBean1 b1, NonOptionalBean2 b2,
...) { ... }
But this requires the creation of four constructors depending on how many conditional beans are present (both, none, exactly one). This works, but in the general case requires an exponential number of constructors - I can only assume there is a better way.
Given the drawbacks of field injection, and my desire to keep my injected beans final
, I am hoping to do better than using setter-injection or field-injection. Perhaps, something that looks like...
public MainService(NonOptionalBean1 b1, NonOptionalBean2 b2,
..., @Optional ComponentA a, @Optional ComponentB b) { ... }
You can use Optional<YourOptionalBean>
with Spring. It works with constructor injection.