Spring Constructor Injection with Collections

We can inject java collections by using constructor injection in spring framework. We can inject following collection by using constructor injection.


  • List
  • Set
  • Map

In this example, there is a library which contains list of book.


Files Required :

  1. Library.java
  2. bean.xml
  3. Test.java

Library.java

package com.jwt.spring;

import java.util.List;

public class Library {
	private int id;
	private String name;
	private List<String> books;

	public Library(int id, String name, List<String> books) {
		this.id = id;
		this.name = name;
		this.books = books;
	}

	public String toString() {
		return "Books Dtails " + books + "Id is: " + id + " Library Name: "
				+ name;
	}

}

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

	<bean id="library" class="com.jwt.spring.Library">
		<constructor-arg value="101"></constructor-arg>
		<constructor-arg value="University Library"></constructor-arg>
		<constructor-arg>
			<list>
				<value>Head First Java</value>
				<value>Mastering EJB</value>
				<value>JSF in Action</value>
			</list>
		</constructor-arg>
	</bean>
</beans>

Test.java

package com.jwt.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"bean.xml");
		Object o = context.getBean("library");
		Library library = (Library) o;
		System.out.println(library);

	}
}



Output :

Books Dtails [Head First Java, Mastering EJB, JSF in Action]Id is: 101 Library Name: University Library






comments powered by Disqus