Spring Inject Set with Example

  • In our Spring Application any Spring Bean contains List type properties,Then Spring Container will use The <list> tag to inject the List into Spring Bean.
  • To do Thsi in applicationContext.xml under the <property> tag we need to use <list> tag and under the list we have to use <value> and <ref> tag.

Tools Used In This Article

  • Spring 3.2.16
  • Maven 4.0.0
  • JDK 1.7

The Project Structure


Maven Dependencies

Add The Following Dependencies to the pom.xml

  • spring-core
  • spring-context

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>HibernateHqlSelectDemo</groupId>
<artifactId>HibernateHqlSelectDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>>spring-core</artifactId>
<version>3.2.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.16.RELEASE</version>
</dependency>

</dependencies>
</project>

Account.java


package com.testpractice;

import java.util.List;

public class Account {



private List accountLists;

public List getAccountLists() {
return accountLists;
}

public void setAccountLists(List accountLists) {
this.accountLists = accountLists;


}

public void showAccountList(){

System.out.println(accountLists);
}


}


applicationContext.xml


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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-2.5.xsd">
<bean id = "account" class ="com.testpractice.Account">

<property name="accountLists">
<list>
<value>1</value>
<value>2</value>
<value>3</value>
<value>4</value>
<value>1</value>
<ref local = "string"></ref>
</list>
</property>

</bean>
<bean id = "string" class = "java.lang.String">
<constructor-arg value = "ABC"/>
</bean>

</beans>

Test.java


package com.testpractice;


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


public class Test {

/**
* @param args
*/
public static void main(String[] args) {

// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
Object object =context.getBean("account");
Account account = (Account)object;

account.showAccountList();


}


}


output



[1, 2, 3, 4, 1, ABC]