I have a class Car
which has a dependency : Motor
My class Car
is like this :
@Component
public class Car {
private Motor motor;
@Autowired
public Car(Motor motor) {
this.motor = motor;
}
public Car() {
this.motor = new Motor("created by Car");
}
I'm not sure how Spring manages what to do : using default/no-args constructor or constructor injection dependency ? Which motor instance should be used ?
CodePudding user response:
Based on Autowired documentation,
The constructor with the greatest number of dependencies that can be satisfied by matching beans in the Spring container will be chosen. If none of the candidates can be satisfied, then a primary/default constructor (if present) will be used.
Meaning, in your case, if Spring boot container finds bean of Motor
during bootstrapping (may be via @Configuraton
or @Component
etc, ) then your Car
bean will get instantiated with constructor based DI & in this case default constructor won't be used for creating Car
bean.
If there is no Motor
bean available during creation of Car
bean, then default constructor is used.
CodePudding user response:
spring always call by default no arg constructor make sure you annotate motar as Component