Home » Spring » Spring Constructor Injection with Collections

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


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;


<beans xmlns="http://www.springframework.org/schema/beans"
	<bean id="library" class="com.jwt.spring.Library">
		<constructor-arg value="101"></constructor-arg>
		<constructor-arg value="University Library"></constructor-arg>
				<value>Head First Java</value>
				<value>Mastering EJB</value>
				<value>JSF in Action</value>


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(
		Object o = context.getBean("library");
		Library library = (Library) o;

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

Previous Next Article
comments powered by Disqus