Reputation: 2066
As far as I know constructors injection enforces mandatory dependencies and setters injection allow optional dependencies, but then...
Wouldn't be possible then this approach ???
@Component
public class Car {
@Autowired(required=false)
public Car(Engine engine, Transmission transmission) {
this.engine = engine;
this.transmission = transmission;
}
}
Upvotes: 3
Views: 930
Reputation: 8651
Your approach won't work as Spring will not inject null
if no bean of given type is found. If you set @Autowired(required=false)
on the setter method, in case there is no such bean this setter won't be called. It is not possible with the constructor.
For Spring
version 4.1+
you can use Java 8 Optional for declaring optional dependencies:
@Component
public class Car {
@Autowired
public Car(Engine engine, Optional<Transmission> transmission) {
this.engine = engine;
this.transmission = transmission.orElse(null);
}
}
In this case Spring will understand that Engine
is required and but Transmission
is optional. So if no bean of type Transmission
is found then Optional.empty()
is injected.
Upvotes: 6