This is an anti pattern, but I am curious what will actually happen.
If you explicitly define a no-args constructor and a constructor with an autowired parameter, how exactly will spring framework initialize it?
@Service
class Clazz {
private MyBean myBean;
public Clazz(){}
@Autowired
public Clazz(MyBean myBean){
this.myBean = myBean;
}
}
On top of above answers, if there is single constructor declared without @autowire, spring uses same constructor for injection.
If there multiple constructors, then Spring uses constructor which is @autowired.
Mentioned in Spring Doc https://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/htmlsingle/#beans-autowired-annotation
As of Spring Framework 4.3, an @Autowired annotation on such a constructor is no longer necessary if the target bean only defines one constructor to begin with. However, if several constructors are available, at least one must be annotated to teach the container which one to use
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With