Spring Collection Injection: How does it actually work

I am learning Java Spring Framework out of personal interest. I am trying to understand how it works. Today I was learning dependency injection in Spring. I started with injecting java collections through xml beans. As you already know, if you want to set a property of primitive type, you need to put exactly the same property name in bean xml definition. I started with that for injecting a List collection named addressList.

I wrote the getter and setter method with convention getAddressList, setAddressList respectively. So if I set the property name to ‘addressList’, Spring context can load the property.

I tested with this class for my beans:

package com.tutorialspoint;
import java.util.*;

public class JavaCollection {
	
	List addressList; 
	//property name is no more important as context communicates with getter and setter
	
	
	public void setAddressList(List addressList)
	{
		System.out.println("Inside setAddressList" + addressList);
		this.addressList = addressList;
	}
	
	public List getAddressList()
	{
		return this.addressList;
	}

}

And a very tiny Bean.xml file

<?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 id="MyCollection" class="com.tutorialspoint.JavaCollection">
   		<property name="addressList">
   			<list>
   			<value>Bangladesh</value>
   			<value>Germany</value>
   			</list>
   		</property>
   </bean>

</beans>

Here is how spring will parse data. When it sees it’s parsing a collection, it automatically assumes there is a setter and getter method. But the names it produced are based solely on the property name in the XML file! So, if you change the property name in the class it will work because Spring wouldn’t even check that. It will always use getter and setters, even for Public properties. So with the same bean file, this code works when creating beans:

package com.tutorialspoint;
import java.util.*;

public class JavaCollection {
	
	List funnyList; 
	//property name is no more important as context communicates with getter and setter
	
	
	public void setAddressList(List addressList)
	{
		System.out.println("Inside setAddressList" + addressList);
		this.funnyList= addressList;
	}
	
	public List getAddressList()
	{
		return this.funnyList;
	}

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s