Datasheet

3. Change the directory back to the /springfirst directory in which pom.xml is located.
4. Now, run the application using Maven 2 with the following command line:
mvn exec:java -Dexec.mainClass=com.wrox.begspring.CalculateSpring –Dexec.args=”3000 3”
First, note that you do not need to recompile at all; you perform this reconfiguration purely by editing
an XML file — the context descriptor. Also notice that the output indicates that the
OpAdd operation and
ScreenWriter have been wired to the CalculateSpring bean. All this has been done automatically
by the Spring container:
The result of 3000 plus 3 is 3003!
How It Works
Even though you have not explicitly wired the OpAdd and ScreenWriter components to the
CalculateSpring bean, the container is smart enough to deduce how the three beans must fit together.
This magic is carried out by the Spring container’s ability to automatically wire together components.
Notice the attribute
autowire=”byType” on the <bean> element for the opsbean. This tells the Spring
container to automatically wire the bean. The container examines the beans for properties that can be set,
and tries to match the type of the property with the beans available. In this case, the
CalculateSpring
bean has two property setters:
public void setOps(Operation ops) {
this.ops = ops;
}
public void setWriter(ResultWriter writer) {
wtr = writer;
}
The first one takes a type of Operation, and the second takes a type of ResultWriter. In the beans.xml
file, the only bean that implements the Operation interface is the add bean, and the only bean that imple-
ments the
ResultWriter interface is the screen bean. Therefore, the Spring container wires the add bean
to the
ops property, and the screen bean to the writer property, automatically.
Autowiring can sometimes simplify the clutter typically found in a large descriptor file. However, explicit
wiring should always be used if there is any chance of autowiring ambiguity.
You can also autowire by other criteria. The following table describes the other varieties of autowiring
supported by Spring 2.
Continued
Value of autowire Attribute Description
byName
The container attempts to find beans with the same name as
the property being wired. For example, if the property to be
set is called
operation, the container will look for a bean with
id=”operation”. If such a bean is not found, an error is raised.
15
Chapter 1: Jump Start Spring 2
01612c01.qxd:WroxPro 10/31/07 10:42 AM Page 15