If there are two constructors annotated with @Autowired, which one the container will use to inject beans to the constructor?
According to the document:
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.
The document does not say which constructor to use in order to inject beans by constructor.
The annotation Javadoc tells you which constructor will be picked - the one with the highest number of arguments that can be resolved. There will probably be an exception if there is still ambiguity because several methods have the same highest number of resolvable arguments.
Tim Holloway wrote:Is it really IntelliJ that fails the compile, or is it the Java compiler itself? The annotation's internal logic may be detecting the violation.
It can't the Java compiler, because there is no way yet to indicate an annotation can only occur once in a class. The only limitations are where the annotation can be put (the target).
IntelliJ is quite smart about a lot of framework annotations. It probably has built-in support for Spring annotations.
Rob Spoor wrote:
It can't the Java compiler, because there is no way yet to indicate an annotation can only occur once in a class.
Not so. Who do you think compiles the annotation? Annotations can basically be designated for either compile-time processing or run-time processing. At compile time, it's certainly not impossible to detect that the same method (or constructor, in this instance) is annotated more than once.
An IDE is no substitute for an Intelligent Developer.
Yes, the Java compiler can catch that one constructor has the same annotation twice. Unless the annotation is repeatable (since Java 8), that's a compiler error. But what the Java compiler cannot (yet) catch is that two constructors have the same annotation (once each). I can write a class with two @Autowired constructors and the Java compiler will not complain. IntelliJ is a bit smarter apparently because it does complain.