Revise documentation for autowiring with annotated constructors
Closes gh-24711
This commit is contained in:
@@ -5085,21 +5085,22 @@ without an `@Autowired` annotation.
|
||||
====
|
||||
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
|
||||
bean. As a consequence, if the `required` attribute is left at its default value `true`,
|
||||
only a single constructor may be annotated with `@Autowired`. If multiple constructors
|
||||
declare the annotation, they will all have to declare `required=false` in order to be
|
||||
considered as candidates for autowiring (analogous to `autowire=constructor` in XML).
|
||||
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.
|
||||
single constructor to begin with, it will always be used, even if not annotated. Note that
|
||||
an annotated constructor does not have to be public.
|
||||
|
||||
The `required` attribute of `@Autowired` is recommended over the deprecated `@Required`
|
||||
annotation on setter methods. Setting the `required` attribute to `false` indicates that
|
||||
the property is not required for autowiring purposes, and 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, and if no value is defined, a
|
||||
corresponding exception is raised.
|
||||
property to be set by any means supported by the container, and if no value is defined,
|
||||
a corresponding exception is raised.
|
||||
====
|
||||
|
||||
Alternatively, you can express the non-required nature of a particular dependency
|
||||
|
||||
Reference in New Issue
Block a user