Spring 3 – Injecting Values with XML Config


Overview

This post demonstrates setting Spring Bean property values using an xml config file.

The example demonstrates the following principles:

  • setter injection
  • constructor injection (by index)
  • multiple argument injection (by name)
  • bean injection by reference
  • list injection (by value and by reference)
  • aliases

Example

The following example is presented as a Maven Project.  The Spring Config (xml) file is stored in src/test/resources.  The Bean (Java) code is stored in src/main/java in the appropriate package; and the JUnit Test (Java) code is stored in src/test/java in the appropriate package.  For the appropriate package, see the package name in each code example.

Spring Config (xml)

The following xml config file presents three main types of beans as follows:

  • Person Bean
    represents a person with a name, age, email and address which is a separate Address Bean
  • Address Bean
    represents an address with a list of lines for street data, a town, county and postcode
  • AddressBook Bean
    represents an address book of people, with a single home Address for each AddressBook bean

Note that aliases are used for a uni address, and a home address.

people1.xml

<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.xsd">

	<!-- Person Beans -->
	<!-- Bean Setter Injection -->
	<bean id="jondoe" class="com.skills421.examples.spring.model.Person">
		<property name="name" value="Jon Doe" />
	</bean>

	<!-- Bean Setter Injection -->
	<bean id="janedoe" class="com.skills421.examples.spring.model.Person">
		<property name="name" value="Jane Doe" />
		<property name="age" value="18" />
		<property name="email" value="jane.doe@gmail.com" />
		<property name="address" ref="london" />
	</bean>

	<!-- Bean Constructor Injection -->
	<bean id="markdoe" class="com.skills421.examples.spring.model.Person">
		<constructor-arg index="0" value="Mark Doe" />
		<constructor-arg index="1" value="19" />
		<constructor-arg index="2" value="mark.doe@gmail.com" />
		<constructor-arg index="3" ref="leeds" />
	</bean>
	
	<!-- Bean Constructor Injection - Alias -->
	<bean id="alexwhite" class="com.skills421.examples.spring.model.Person">
		<constructor-arg index="0" value="Alex White" />
		<constructor-arg index="1" value="19" />
		<constructor-arg index="2" value="alex.white@gmail.com" />
		<constructor-arg index="3" ref="uni" />
	</bean>
	
	<!-- Bean Constructor Injection - Alias -->
	<bean id="alicejenkins" class="com.skills421.examples.spring.model.Person">
		<property name="name" value="Alice Jenkins" />
		<property name="age" value="18" />
		<property name="email" value="alice.jenkins@gmail.com" />
		<property name="address" ref="uni" />
	</bean>

	<!-- Bean Constructor Injection - with Inner Beans -->
	<bean id="jimdoe" class="com.skills421.examples.spring.model.Person">
		<constructor-arg index="0" value="Jim Doe" />
		<constructor-arg index="1" value="15" />
		<constructor-arg index="2" value="jim.doe@gmail.com" />
		<constructor-arg index="3">
			<!-- Inner Bean Constructor Injection -->
			<bean class="com.skills421.examples.spring.model.Address">
				<constructor-arg index="0">
					<list>
						<value>18 Main Street</value>
						<value>Little Somewhere</value>
					</list>
				</constructor-arg>
				<constructor-arg index="1" value="Leeds" />
				<constructor-arg index="2" value="West Yorkshire" />
				<constructor-arg index="3" value="LS1 1AA" />
			</bean>
		</constructor-arg>
	</bean>
	
	<!-- Bean Setter Injection - List of Previous Addresses -->
	<bean id="papadoe" class="com.skills421.examples.spring.model.Person">
		<property name="name" value="Papa Doe" />
		<property name="age" value="54" />
		<property name="email" value="papa.doe@gmail.com" />
		<property name="address" ref="london" />
		<property name="previousAddresses">
			<list>
				<ref bean="uni" />
				<ref bean="manchester" />
			</list>
		</property>
	</bean>
	
	<!-- Bean Constructor Injection - List of Previous Addresses -->
	<bean id="mamadoe" class="com.skills421.examples.spring.model.Person">
		<constructor-arg index="0" value="Mama Doe" />
		<constructor-arg index="1" value="42" />
		<constructor-arg index="2" value="mama.doe@gmail.com" />
		<constructor-arg index="3" ref="london" />
		<property name="previousAddresses">
			<list>
				<ref bean="manchester" />
			</list>
		</property>
	</bean>
	
	<!-- Address Beans -->
	<!-- Bean Setter Injection -->
	<bean id="london" class="com.skills421.examples.spring.model.Address">
		<property name="addressLines">
			<list>
				<value>House of Commons</value>
				<value>Parliament Square</value>
			</list>
		</property>
		<property name="town" value="London" />
		<property name="county" value="Greater London" />
		<property name="postcode" value="SW1 1AA" />
	</bean>

	<!-- Bean Constructor Injection -->
	<bean id="leeds" class="com.skills421.examples.spring.model.Address">
		<constructor-arg index="0">
			<list>
				<value>23 Main Street</value>
				<value>Little Somewhere</value>
			</list>
		</constructor-arg>
		<constructor-arg index="1" value="Leeds" />
		<constructor-arg index="2" value="West Yorkshire" />
		<constructor-arg index="3" value="LS1 1AA" />
	</bean>
	
	<!-- Bean Constructor Injection -->
	<bean id="manchester" class="com.skills421.examples.spring.model.Address">
		<constructor-arg index="0">
			<list>
				<value>14 Town Plaza</value>
				<value>Inner Township</value>
			</list>
		</constructor-arg>
		<constructor-arg index="1" value="Manchester" />
		<constructor-arg index="2" value="Greater Manchester" />
		<constructor-arg index="3" value="MC15 1AA" />
	</bean>
	
	<!--  AddressBook -->
	<bean id="emptyAddressBook" class="com.skills421.examples.spring.model.AddressBook" autowire="byName">
	</bean>
	
	<bean id="DoeAddressBook1" class="com.skills421.examples.spring.model.AddressBook" autowire="byName">
		<property name="contacts">
			<list>
				<ref bean="jondoe" />
				<ref bean="janedoe" />
				<ref bean="markdoe" />
				<ref bean="papadoe" />
				<ref bean="mamadoe" />
			</list>
		</property>
	</bean>
	
	<bean id="DoeAddressBook2" class="com.skills421.examples.spring.model.AddressBook" autowire="byName">
		<property name="contacts">
			<list value-type="com.skills421.examples.spring.model.Person">
				<ref bean="jondoe" />
				<ref bean="janedoe" />
				<ref bean="markdoe" />
				<ref bean="papadoe" />
				<ref bean="mamadoe" />
			</list>
		</property>
	</bean>
	
	<bean id="familyAddressBook" class="com.skills421.examples.spring.model.AddressBook" autowire="byName" scope="prototype">
		<property name="contacts">
			<list value-type="com.skills421.examples.spring.model.Person">
				<ref bean="jondoe" />
				<ref bean="janedoe" />
				<ref bean="markdoe" />
				<ref bean="papadoe" />
				<ref bean="mamadoe" />
			</list>
		</property>
	</bean>
	
	<!-- Aliases -->
	<alias name="leeds" alias="uni" />
	<alias name="london" alias="home" />
	
</beans>

Java Code (Beans)

Person.java

package com.skills421.examples.spring.model;

import java.util.List;

public class Person
{
	private String name;
	private int age;
	private String email;

	private Address address;

	private List</pre>
<address>previousAddresses;

 public Person()
 {

 }

 public Person(String name, int age, String email, Address address)
 {
 this.name = name;
 this.age = age;
 this.email = email;
 this.address = address;
 }

 public String getName()
 {
 return name;
 }

 public void setName(String name)
 {
 this.name = name;
 }

 public int getAge()
 {
 return age;
 }

 public void setAge(int age)
 {
 this.age = age;
 }

 public String getEmail()
 {
 return email;
 }

 public void setEmail(String email)
 {
 this.email = email;
 }

 public Address getAddress()
 {
 return address;
 }

 public void setAddress(Address address)
 {
 this.address = address;
 }

 public List
<address>getPreviousAddresses()
 {
 return previousAddresses;
 }

 public void setPreviousAddresses(List
<address>previousAddresses)
 {
 this.previousAddresses = previousAddresses;
 }

 public String toString()
 {
 StringBuilder sb = new StringBuilder("Person[");

 sb.append("name="+name);
 sb.append(", age="+age);
 sb.append(", email="+email);
 sb.append(", address="+address);

 if(previousAddresses!=null)
 {
 sb.append(", previousAddresses=[");

 int count = 0;

 for(Address prevAddress : previousAddresses)
 {
 if(count>0) sb.append(", ");
 sb.append(prevAddress);
 count++;
 }

 sb.append("]");
 }

 sb.append("]");

 return sb.toString();
 }
}

Address.java

package com.skills421.examples.spring.model;

import java.util.List;

public class Address
{
	private List addressLines;
	private String town;
	private String county;
	private String postcode;

	public Address()
	{

	}

	public Address(ListaddressLines, String town, String county, String postcode)
	{
		this.addressLines = addressLines;
		this.town = town;
		this.county = county;
		this.postcode = postcode;
	}

	public List getAddressLines()
	{
		return addressLines;
	}

	public void setAddressLines(List addressLines)
	{
		this.addressLines = addressLines;
	}

	public String getTown()
	{
		return town;
	}

	public void setTown(String town)
	{
		this.town = town;
	}

	public String getCounty()
	{
		return county;
	}

	public void setCounty(String county)
	{
		this.county = county;
	}

	public String getPostcode()
	{
		return postcode;
	}

	public void setPostcode(String postcode)
	{
		this.postcode = postcode;
	}

	public String toString()
	{
		StringBuilder sb = new StringBuilder("Address[");

		if(addressLines!=null)
		{
			sb.append("addreslines=[");

			int count=0;

			for(String line : addressLines)
			{
				if(count>0) sb.append(", ");
				sb.append(line);
				count++;
			}

			sb.append("]");
		}

		sb.append(", town="+town);
		sb.append(", county="+county);
		sb.append(", postcode="+postcode);
		sb.append("]");

		return sb.toString();
	}
}

AddressBook.java

package com.skills421.examples.spring.model;

import java.util.List;

public class AddressBook
{
	private Address home;
	private List contacts;

	public Address getHome()
	{
		return home;
	}

	public void setHome(Address home)
	{
		this.home = home;
	}

	public List getContacts()
	{
		return contacts;
	}

	public void setContacts(List contacts)
	{
		this.contacts = contacts;
	}

	public String toString()
	{
		StringBuilder sb = new StringBuilder("AddressBook[");

		sb.append("home="+home);

		if(contacts!=null)
		{
			int count=0;

			for(Person person : contacts)
			{
				if(count>0) sb.append(", ");
				sb.append(person);
				count++;
			}
		}

		sb.append("]");

		return sb.toString();
	}

}

JUnit Test

I have written each piece of code to test the beans as a JUnit Test. In order to present the output, I have printed the values from each test instead of checking for expected values.

Note that this example uses a ClassPathXmlApplicationContext.  This is created in the @BeforeClass and closed in the @AfterClass.  These methods are executed once before all the tests run, and once after all the tests have completd.

The @After method runs after each test and simply prints a blank line to separate the output.

The first few tests print specific named beans.

testAllBeans() prints every bean that is instantiated within the ApplicationContext

testAllPersonBeans(), testAllAddressBeans() and testAllAddressBookBeans() use generics to print only the specific bean types the methods are interested in

Finally, testFamilyAddressBook() demonstrates the bean scopes of Singleton (default) and Prototype (specified in the config xml for familyAddressBook)

TestPeople.java

package com.skills421.example.spring;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.skills421.examples.spring.model.Address;
import com.skills421.examples.spring.model.AddressBook;
import com.skills421.examples.spring.model.Person;

public class TestPeople
{
	private static AbstractApplicationContext context;

	@BeforeClass
	public static void setupAppContext()
	{
		context = new ClassPathXmlApplicationContext("people1.xml");
	}

	@AfterClass
	public static void closeAppContext()
	{
		if(context!=null)
		{
			context.close();
		}
	}

	@After
	public void printBlankLine()
	{
		System.out.println();
	}

	@Test
	public void test1()
	{
		System.out.println("jondoe");
		Person person = context.getBean("jondoe",Person.class);
		System.out.println(person);
	}

	@Test
	public void test2()
	{
		System.out.println("london");
		Address address = context.getBean("london",Address.class);
		System.out.println(address);
	}

	@Test
	public void test3()
	{
		System.out.println("janedoe");
		Person person = context.getBean("janedoe",Person.class);
		System.out.println(person);
	}

	@Test
	public void testAllBeans()
	{
		System.out.println("*** All Beans ***\n");
		for(String beanName : context.getBeanDefinitionNames())
		{
			System.out.println("Bean: "+beanName);
			System.out.println(context.getBean(beanName));
			System.out.println();
		}
	}

	@Test
	public void testAllPersonBeans()
	{
		System.out.println("*** Person Beans ***\n");
		for(String beanName : context.getBeanNamesForType(Person.class))
		{
			System.out.println("Bean: "+beanName);
			System.out.println(context.getBean(beanName));
			System.out.println();
		}
	}

	@Test
	public void testAllAddressBeans()
	{
		System.out.println("*** Address Beans ***\n");
		for(String beanName : context.getBeanNamesForType(Address.class))
		{
			System.out.println("Bean: "+beanName);
			System.out.println(context.getBean(beanName));
			System.out.println();
		}
	}

	@Test
	public void testAllAddressBookBeans()
	{
		System.out.println("*** AddressBook Beans ***\n");
		for(String beanName : context.getBeanNamesForType(AddressBook.class))
		{
			System.out.println("Bean: "+beanName);
			System.out.println(context.getBean(beanName));
			System.out.println();
		}
	}

	@Test
	public void testFamilyAddressBook()
	{
		System.out.println("*** Family AddressBook ***\n");

		// familyAddressBook - scope = prototype
		AddressBook addr1 = context.getBean("familyAddressBook", AddressBook.class);
		AddressBook addr2 = context.getBean("familyAddressBook", AddressBook.class);

		System.out.println(addr1);
		System.out.println(addr2);
		System.out.println(addr1==addr2);

		// familyAddressBook - scope = default = singleton
		addr1 = context.getBean("DoeAddressBook1", AddressBook.class);
		addr2 = context.getBean("DoeAddressBook1", AddressBook.class);

		System.out.println(addr1);
		System.out.println(addr2);
		System.out.println(addr1==addr2);

		System.out.println("*** AddressBook Beans ***\n");
		for(String beanName : context.getBeanNamesForType(AddressBook.class))
		{
			System.out.println("Bean: "+beanName);
		}
	}
}

Project Configuration

pom.xml

4.0.0
	com.skills421.examples.spring
	Spring3.2.6.Demo
	0.0.1-SNAPSHOT

		3.2.6.RELEASE

		<!-- Spring 3 dependencies -->

			org.springframework
			spring-core
			${spring.version}

			org.springframework
			spring-context
			${spring.version}

		<!-- JUnit -->

			junit
			junit
			4.11

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s