Java Reference
In-Depth Information
1-3. Auto-Wiring Beans with XML Configuration
Problem
When a bean requires access to another bean, you can wire it by specifying the reference explicitly.
However, if your container can wire your beans automatically, it can save you the trouble of configuring
the wirings manually.
Solution
The Spring IoC container can help you to wire your beans automatically. You only have to specify the
auto-wiring mode in the autowire attribute of <bean> . Table 1-1 lists the auto-wiring modes supported
by Spring.
Table 1-1. Auto-Wiring Modes Supported by Spring
Mode
Description
no *
No auto-wiring will be performed. You must wire the dependencies explicitly.
byName
For each bean property, wire a bean with the same name as the property.
byType
For each bean property, wire a bean whose type is compatible with that of the property.
If more than one bean is found, an UnsatisfiedDependencyException will be thrown.
constructor
For each argument of each constructor, first find a bean whose type is compatible with
the argument's. Then pick the constructor with the most matching arguments. In case
of any ambiguity, an UnsatisfiedDependencyException will be thrown.
autodetect
If a default constructor with no argument is found, the dependencies will be auto-wired
by type. Otherwise, they will be auto-wired by constructor.
* The default mode is no , but this can be changed by setting the default-autowire attribute of the
<beans> root element. This default mode will be overridden by a bean's own mode if specified.
Although the auto-wiring feature is very powerful, the cost is that it will reduce the readability of
your bean configurations. Because auto-wiring is performed by Spring at runtime, you cannot derive
how your beans are wired from the bean configuration file. In practice, I recommend applying auto-
wiring only in applications whose component dependencies are not complicated.
 
Search WWH ::




Custom Search