Spring bean auto-wiring modes
We have seen many examples in the previous pages on how to declare beans and how to inject dependencies using constructor-arg
and property tags. Spring provides another feature called bean auto-wiring, which will cut down the above said configurations in the xml
based configuration file. When using XML-based configuration metadata, the autowire mode for a bean definition is specified by using the
autowire attribute of the <bean/> element.
Multiple autowiring modes are available to instruct spring container, the details are given below, more examples are followed
in the next pages.
no: No autowiring at all. Bean references must be defined via a ref element. This is the default, and changing
this is discouraged for larger deployments, since explicitly specifying collaborators gives greater control and clarity. To some extent, it
is a form of documentation about the structure of a system.
byName: Autowiring by property name. This option will inspect the container and look for a bean named exactly
the same as the property which needs to be autowired. For example,
if you have a bean definition which is set to autowire by name, and it contains a master property (that is, it has a setMaster(..) method),
Spring will look for a bean definition named master, and use it to set the property.
byType: Allows a property to be autowired if there is exactly one bean of the property type in the container.
If there is more than one, a fatal exception is thrown, and this indicates that you may not use byType autowiring for that bean. If there
are no matching beans, nothing happens; the property is not set. If this is not desirable, setting the dependency-check="objects" attribute
value specifies that an error should be thrown in this case.
constructor: This is analogous to byType, but applies to constructor arguments. If there isn't exactly one bean
of the constructor argument type in the container, a fatal error is raised.
autodetect: Chooses constructor or byType through introspection of the bean class. If a default constructor is found,
the byType mode will be applied.
Note that explicit dependencies in property and constructor-arg settings always override autowiring. Please also note that
it is not currently possible to autowire so-called simple properties such as primitives, Strings, and Classes (and arrays of such simple properties).
(This is by-design and should be considered a feature.) When using either the byType or constructor autowiring mode, it is possible to wire arrays
and typed-collections. In such cases all autowire candidates within the container that match the expected type will be provided to satisfy the
dependency. Strongly-typed Maps can even be autowired if the expected key type is String. An autowired Map's values will consist of all bean instances
that match the expected type, and the Map's keys will contain the corresponding bean names.
|