XML configuration is one way to manage (create, destroy, set arguments,…) beans. Below some example.
This example depends on the previous post First Time Spring.
( 1 ) Pass simple arguments to a bean’s constructor
circle = new Circle(5);
<bean id="circle2" class="com.hmkcode.beans.Circle"> <constructor-arg value="5"/> </bean>
( 2 ) Passing an object as an argument to a bean’s constructor
shapePainter = new ShapePainter(circle, “blue”)
<bean id="circle" class="com.hmkcode.beans.Circle"/>
<bean id="shapePainter" class="com.hmkcode.beans.ShapePainter">
<constructor-arg ref="circle"/>
<constructor-arg value="blue"/>
</bean>
( 3 ) Creating single or many beans set scope=(singleton vs. prototype)
By default Spring create a single bean so setting the scope attribute as singleton is optional
<bean id="circle" class="com.hmkcode.beans.Circle"/>
To create more than one change the scope to prototype
<bean id="circle" class="com.hmkcode.beans.Circle" scope="prototype"/>
( 4 ) Set bean simple property using set method
circle.setRadius(4.0)
<bean id="circle" class="com.hmkcode.beans.Circle"> <property name="radius" value="4.0"/> </bean>
( 5 )Set bean object property using set method
shapePainter.setShape(circle)
<bean id="shapePainter" class="com.hmkcode.beans.ShapePainter"> <property name="shape" ref="circle"/> </bean>
Or
shapePainter.setShape(new Circle())
<bean id="shapePainter" class="com.hmkcode.beans.ShapePainter">
<property name="shape">
<bean class="com.hmkcode.beans.Circle" />
</property>
</bean>
( 6 ) Calling a method once a bean is initialized init-method=”methodName”
<bean id="shapePainter" class="com.hmkcode.beans.ShapePainter" init-method="paint"> <property name="shape"> <bean class="com.hmkcode.beans.Circle" /> </property> <property name="color" value="blue"/> </bean>
Also, you can call a method before a bean is “destroyed” using destroy-method=”methodName”
Download the “updated” source code FirstTimeSpring.zip


