Prior to this commit, there was some ambiguity surrounding semantics
for @Autowired constructors and `required = true`, especially for
multiple @Autowired constructors.
This commit improves the documentation in the Javadoc for @Autowired as
well as in the reference manual.
Closes gh-23263
@ -4530,16 +4530,22 @@ indicating __required__ dependencies. This behavior can be changed as demonstrat
@@ -4530,16 +4530,22 @@ indicating __required__ dependencies. This behavior can be changed as demonstrat
[NOTE]
====
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 __required__ attribute of `@Autowired` is recommended over the `@Required` annotation.
The __required__ attribute indicates that the property is not required for autowiring
purposes, the property is ignored if it cannot be autowired. `@Required`, on the other
hand, is stronger in that it enforces the property that was set by any means supported
by the container. If no value is injected, a corresponding exception is raised.
Only one constructor of any given bean class may declare `@Autowired` with the `required`
attribute set to `true`, indicating _the_ constructor to autowire when used as a Spring
bean. Furthermore, if the `required` attribute is set to `true`, only a single
constructor may be annotated with `@Autowired`. If multiple _non-required_ constructors
declare the annotation, they will be considered as candidates for autowiring. 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. If a class only declares a
single constructor to begin with, it will always be used, even if not annotated. An
annotated constructor does not have to be public.
The `required` attribute of `@Autowired` is recommended over the `@Required` annotation
on setter methods. The `required` attribute indicates that the property is not required
for autowiring purposes. The property is ignored if it cannot be autowired. `@Required`,
on the other hand, is stronger in that it enforces the property to be set by any means
supported by the container. If no value is defined, a corresponding exception is raised.
====
Alternatively, you may express the non-required nature of a particular dependency