Spring - Collection
Say for example the 'Car' class has a reference to many instances of the 'Wheel' class. In simple words the 'Car' class can hold many 'Wheel' objects.
In such cases we need to go with Java Collection. So, either we can go with a List of a Set or a Map.
Let us see with the below example how to implement Collection with Spring :
Wheel class
class Wheel {
String tyreType;
//-- Getters and Setters --
}
Car Class
class Car {
List <Wheel> wheelList = new ArrayList < >();
//-- Getters and Setters --
}
Since the 'Car' class has a reference to many 'Wheel' instances, we have used 'List' to hold the 'Wheel' objects.
List <Wheel> wheelList = new ArrayList < >();
Now, let us define the 'application-context.xml'
application-context.xml
<?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-3.0.xsd">
<bean name = "car" class = "Car">
<property name = "wheelList"/>
<list>
<ref bean="wheelActual"/>
<ref bean="wheelSpare"/>
</list>
</property>
</bean>
<bean name="wheelActual" class = "Wheel">
<property name = "wheel" value="Actual Tire"/>
</bean>
<bean name="wheelSpare" class = "Wheel">
<property name = "wheel" value="Spare Tire"/>
</bean>
</beans >
In the above case we have asked spring to create two 'Wheel' beans 'wheelActual' and 'wheelSpare'
<bean name="wheelActual" class = "Wheel">
<property name = "wheel" value="Actual Tire"/>
</bean>
<bean name="wheelSpare" class = "Wheel">
<property name = "wheel" value="Spare Tire"/>
</bean>
And using the <list> tag we have referenced 'wheelActual' and 'wheelSpare' bean using the <ref> tag in the <bean ..> tag of 'Car' .
<list>
<ref bean="wheelActual"/>
<ref bean="wheelSpare"/>
</list>
Finally, in the main() method we define our application code to interact with spring.
import org.springframework.context.ApplicationContext;
public class FirstSpringApp {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml");
Car car = (Car)applicationContext.getBean("car");
for(Wheel wheel : car.getWheelList()) {
System.out.println("The Car tire type is : "+wheel.getTireType());
}
}
Output :
The Car tire type is : Actual Tire
The Car tire type is : Spare Tire
So, Spring has already created the 'Car' bean and also instantiated the 'Wheel' List.
And in the 'for' loop we are getting the List of 'Wheel' beans from the 'Car' bean and displaying the 'tireType' of 'Wheel'.