Spring spel list map example

Spring SpEL List/Map:

Spring spel provides the facility to get values from List or Map. It works same as in java.

Example:

MapListTest.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.springframework.stereotype.Component;
 
@Component("mapListTestBean")
public class MapListTest {
	private Map<String, String> map;
	private List<String> list;
 
	public MapListTest() {
		map = new HashMap<String, String>();
		map.put("stu1", "Mahesh");
		map.put("stu2", "Vivek");
		map.put("stu3", "Bharat");
 
		list = new ArrayList<String>();
		list.add("Nidhi");
		list.add("Prabhjot");
		list.add("Amani");
 
	}
 
	public Map<String, String> getMap() {
		return map;
	}
 
	public void setMap(Map<String, String> map) {
		this.map = map;
	}
 
	public List<String> getList() {
		return list;
	}
 
	public void setList(List<String> list) {
		this.list = list;
	}
}

Student.java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
@Component("studentBean")
public class Student {
	@Value("#{mapListTestBean.map['stu1']}")
	private String stu1;	
 
	@Value("#{mapListTestBean.list[0]}")
	private String list;
 
	public String getStu1() {
		return stu1;
	}
 
	public void setStu1(String stu1) {
		this.stu1 = stu1;
	}
 
	public String getList() {
		return list;
	}
 
	public void setList(String list) {
		this.list = list;
	}
 
}

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
 <context:component-scan base-package="com.w3spoint.business" />
 
</beans>

Test.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
/**
 * Spring SPEL Lists, Maps example.
 * @author w3spoint
 */
public class Test {
 public static void main(String args[]){	
  //Get application context object.
  ApplicationContext context = 
	new ClassPathXmlApplicationContext("applicationContext.xml");
 
  //Get studentBean.
  Student student = (Student) context.getBean("studentBean");
 
  //Print student properties.
  System.out.println("From Map: "+student.getStu1()); 
  System.out.println("From List: "+student.getList()); 
 }
}

Output:

From Map: Mahesh
From List: Nidhi

  Download this example.  

Please follow and like us:
Content Protection by DMCA.com