Spring documentation says this:
Only one annotated constructor per class can be marked as required, but multiple non-required constructors can be annotated. In that case, each is considered among the candidates and Spring uses the greediest constructor whose dependencies can be satisfied — that is, the constructor that has the largest number of arguments. The constructor resolution algorithm is the same as for non-annotated classes with overloaded constructors, just narrowing the candidates to annotated constructors.
I tested it and I get an error as soon as I have another constructor marked by @Autowired
package com.example.demo.constructorinjection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ConstructorInjectComponent {
private InjectionServiceOne injectionServiceOne;
private InjectionServiceTwo injectionServiceTwo;
@Autowired(required = true)
public constructorInjectComponent(InjectionServiceOne injectionServiceOne,
InjectionServiceTwo injectionServiceTwo) {
this.injectionServiceOne = injectionServiceOne;
this.injectionServiceTwo = injectionServiceTwo;
}
@Autowired(required = false)
public constructorInjectComponent(InjectionServiceTwo injectionServiceTwo) {
this.injectionServiceTwo = injectionServiceTwo;
}
@Autowired(required = false)
public constructorInjectComponent(InjectionServiceOne injectionServiceOne) {
this.injectionServiceOne = injectionServiceOne;
}
@Scheduled(fixedRate=1000L)
public void allFieldsConstructorInjectionTest() {
System.err.println("constructorInjection " + injectionServiceOne.method() + " " + injectionServiceTwo.method());
}
}
Error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'constructorInjectComponent': Invalid autowire-marked constructor: public com.example.demo.constructorinjection.constructorInjectComponent(com.example.demo.constructorinjection.InjectionServiceOne). Found constructor with 'required' Autowired annotation already: public com.example.demo.constructorinjection.constructorInjectComponent(com.example.demo.constructorinjection.InjectionServiceOne,com.example.demo.constructorinjection.InjectionServiceTwo) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:314) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:1269) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
Question:
Why can't I have more than one constructors marked with @Autowired? Spring documentation clearly says I can have more than one constructor marked with @Autowired.
@Autowired. - Faraz