this.someValue = "Number: " + Integer.toString(someValue);
}
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:app-context-xml.xml");
ctx.refresh();
ConstructorConfusion cc = (ConstructorConfusion) ctx.getBean("constructorConfusion");
System.out.println(cc);
}
public String toString() {
return someValue;
}
}
Here, you can clearly see what this code does--it simply retrieves a bean of type
ConstructorConfusion from ApplicationContext and writes the value to console output. Now look at the
configuration code in Listing 4-32 (app-context-xml.xml).
Listing 4-32. Confused Constructors
<bean id="constructorConfusion"
class="com.apress.prospring3.ch4.xml.ConstructorConfusion">
<constructor-arg>
<value>90</value>
</constructor-arg>
</bean>
Which of the constructors is called in this case? Running the example yields the following output:
ConstructorConfusion(String) called
90
This shows that the constructor with the String argument was called. This is not the desired effect,
since we want to prefix any integer values passed in using Constructor Injection with Number:, as shown
in the int constructor. To get around this, we need to make a small modification to the configuration,
shown in Listing 4-33 (app-context-xml.xml).
Listing 4-33. Overcoming Constructor Confusion
<bean id="constructorConfusion"
class="com.apress.prospring3.ch4.xml.ConstructorConfusion">
<constructor-arg type="int">
<value>90</value>
</constructor-arg>
</bean>
Notice now that the <constructor-arg> tag has an additional attribute, type, that specifies the type
of argument Spring should look for. Running the example again with the corrected configuration yields
the correct output:
ConstructorConfusion(int) called
Number: 90
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home