Datasheet

the required resource and then injects it into the component, effectively inverting the control over the
selection of the resource from the component to the container.
Figure 1-3
Dependency Injection
Since the Spring code shown is dependent on the availability of the DataSource instance to work, and
the instance is injected into the component via the
setDs() method, this technique is often referred to as
dependency injection. In fact, the use of the setter method,
setDS(), to inject the DataSource code depend-
ency is known as setter injection. Spring also supports constructor injection, in which a dependent resource
is injected into a bean via its constructor.
Try It Out Creating a Dependency Injection
To see dependency injection in action, you do not even have to rebuild your project — since beans are
wired via the context descriptor in Spring.
1. Go back to the src/chapter1/springfirst directory and run CalculateSpring:
mvn exec:java -Dexec.mainClass=com.wrox.begspring.CalculateSpring –Dexec.args=”3000 3”
The current bean is autowired with an Operation implementation that adds two numbers
together. And you see the output:
The result of 3000 plus 3 is 3003!
2. Change the directory to edit the context descriptor in the src/chapter1/springfirst/
target/classes
directory:
cd src/chatper1/springfirst/target/classes
CalculateSpring (component)
2. Injects ScreenWriter
for writer property
Container
IoC Container
OpMultiply ScreenWriter
OpMultiply ScreenWriter
1. Give me OpMultiply
2. Here is OpMultiply
3. Give me ScreenWriter
4. Here is ScreenWriter
Calculate (component)
ops property
writer property
1. Injects OpMultiply
for ops property
OpMultiply
ScreenWriter
18
Chapter 1: Jump Start Spring 2
01612c01.qxd:WroxPro 10/31/07 10:42 AM Page 18