Datasheet
3. Now, modify beans.xml to use the OpMultiply implementation instead: edit the file to match
the highlighted lines shown here:
<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd”>
<bean id=”screen” class=”com.wrox.begspring.ScreenWriter” />
<bean id=”multiply” class=”com.wrox.begspring.OpMultiply” />
<bean id=”add” class=”com.wrox.begspring.OpAdd” />
<bean id=”opsbean” class=”com.wrox.begspring.CalculateSpring”>
<property name=”ops” ref=”multiply” />
<property name=”writer” ref=”screen”/>
</bean>
</beans>
4. Change the directory back to the /springfirst directory, where pom.xml is located, and try
running the command again:
mvn exec:java -Dexec.mainClass=com.wrox.begspring.CalculateSpring –Dexec.args=”3000 3”
This time, the output is as follows:
The result of 3000 times 3 is 9000!
The application’s behavior has been altered, and a different component injected into the setter, without
any code recompilation.
How It Works
The CalculateSpring component code has a setter for the ops property, enabling the Spring IoC con-
tainer to inject the dependency into the component during runtime. The following code shows the
setter
method in the highlighted portion:
package com.wrox.begspring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class CalculateSpring {
private Operation ops;
private ResultWriter wtr;
public void setOps(Operation ops) {
this.ops = ops;
}
public void setWriter(ResultWriter writer) {
wtr = writer;
}
19
Chapter 1: Jump Start Spring 2
01612c01.qxd:WroxPro 10/31/07 10:42 AM Page 19