Spring EL Map, List and Array Examples

0

In this article, we demonstrate the use Spring EL to access the values of Array and List. We will also show you to use Spring EL to access the key and value pair of Map. We will see examples of spring EL in annotation as well as spring context XML file.

This example uses the following frameworks:

  1. Maven 3.2.3
  2. Spring 4.1.5.RELEASE
  3. Eclipse  as the IDE, version Luna 4.4.1.

Dependencies

Add the following dependencies:

  1. spring-core
  2. spring-context
  3. spring-beans

pom.xml:

<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>com.javarticles.spring</groupId>
	<artifactId>springListExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
	</dependencies>

	<properties>
		<spring.version>4.1.6.RELEASE</spring.version>
	</properties>

</project>

Spring EL Array Example

In this example, we will see how to use of Spring EL in constructing an array and retrieving array elements.

We first need a simple bean which contains an integer array. We will now use spring EL to initialize the array.

ArrayBean:

package com.javarticles.spring;

import java.util.Arrays;


public class ArrayBean {

    private Integer[] intArray;

    public Integer[] getIntArray() {
        return intArray;
    }

    public void setIntArray(Integer[] intArray) {
        this.intArray = intArray;
    }      
    
    public String toString() {
        return Arrays.asList(intArray).toString();
    }
}

As you can see below, we have initialized the integer array using spring EL #{new int[]{1,2,3,4}}.

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>

<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.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<context:component-scan base-package="com.javarticles.spring" />

	<bean id="arrayBean" class="com.javarticles.spring.ArrayBean">
		<property name="intArray" value="#{new int[]{1,2,3,4}}" />
	</bean>
</beans>

Let’s achieve the same using annotation. In the below bean, we initialize intArray using specifying spring expression #{new int[]{1, 3, 5, 7}} in @Value annotation. The spring EL used in initializing array is similar to the way we construct array in java.

In the second spring EL example, we show how to get an array element using spring expression. We initialize secondElement integer variable with the second element of ArrayBean.initArray. The expression used is #{arrayBean.intArray[1]}. arrayBean is the bean ID and intArray is its member. See Spring EL property for more examples.

SpringElArrayBean:

package com.javarticles.spring;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("springElArrayBean")
public class SpringElArrayBean {

    @Value("#{new int[]{1, 3, 5, 7}}")
    private Integer[] intArray;
    
    @Value("#{arrayBean.intArray[1]}")
    private Integer secondElement;

    public Integer[] getIntArray() {
        return intArray;
    }

    public Integer getSecondElement() {
        return secondElement;
    }         
}

In the below class, we run the Spring EL Array example. The spring context is loaded and then we retrieve the arrayBean and springElArrayBean and verify that the members are properly initialized.

SpringElArrayExample:

package com.javarticles.spring;

import java.util.Arrays;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringElArrayExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            ArrayBean arrayBean = (ArrayBean) context.getBean("arrayBean");
            System.out.println("Int Array: " + arrayBean);
            
            System.out.println("SpringElArrayBean configured using @Value");
            SpringElArrayBean springElArrayBean = (SpringElArrayBean) context.getBean("springElArrayBean");
            System.out.println("intArray: " + Arrays.asList(springElArrayBean.getIntArray()));
            System.out.println("secondElement: " + springElArrayBean.getSecondElement());             
        } finally {
            context.close();
        }
    }
}

Output:

Int Array: [1, 2, 3, 4]
SpringElArrayBean configured using @Value
intArray: [1, 3, 5, 7]
secondElement: 2

Spring EL List Example

In this example, we will see how to use Spring EL in assigning an entire list, getting a specific element from list and then checking whether the list contains an element we are interested in.
Here is a simple list bean we will use in our example.

ListBean:

package com.javarticles.spring;

import java.util.List;

public class ListBean {

    private List intList;

    public List getIntList() {
        return intList;
    }

    public void setIntList(List intList) {
        this.intList = intList;
    }       
}

Here is another bean which we will use both in list and map examples. Its a tutorial bean which contains properties related to stuff that make the tutorial, for example, default topics that are taught, the tutorial price, some hot topics.

Tutorial:

package com.javarticles.spring;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Tutorial {
    private String name;    
    private List defaultTopics = new ArrayList<>();
    private Map<String, String> hotTopics = new HashMap<String, String>();
    private Integer tutorialPrice;
    private Tutorial programmingTutorial;    

    public Tutorial(){}
    
    public Tutorial(List topicsList){
        this.defaultTopics = topicsList;
    }

    public String getName() {
        return name;
    }

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

    public List getDefaultTopics() {
        return defaultTopics;
    }

    public void setDefaultTopics(List topicsList) {
        this.defaultTopics = topicsList;
    }

    public String toString() {
        return name + defaultTopics;
    }

    public Map<String, String> getHotTopics() {
        return hotTopics;
    }

    public void setHotTopics(Map<String, String> hotTopics) {
        this.hotTopics = hotTopics;
    }

    public Integer getTutorialPrice() {
        return tutorialPrice;
    }

    public void setTutorialPrice(Integer tutorialPrice) {
        this.tutorialPrice = tutorialPrice;
    }       
    
    public Tutorial getProgrammingTutorial() {
        return programmingTutorial;
    }

    public void setProgrammingTutorial(Tutorial programmingTutorial) {
        this.programmingTutorial = programmingTutorial;
    }
}

Let’s define the list bean and the tutorial bean in spring context XML.

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>

<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.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<context:component-scan base-package="com.javarticles.spring" />

	<bean id="arrayBean" class="com.javarticles.spring.ArrayBean">
		<property name="intArray" value="#{new int[]{1,2,3,4}}" />
	</bean>

	<bean id="listBean" class="com.javarticles.spring.ListBean">
		<property name="intList">
			<list>
				<value>1</value>
				<value>3</value>
				<value>5</value>
				<value>7</value>
			</list>
		</property>
	</bean>

	<bean id="tutorial" class="com.javarticles.spring.Tutorial">
		<property name="name" value="Current Hot Topics" />
		<property name="tutorialPrice" value="300" />
		<property name="defaultTopics">
			<list>
				<value>Java Core</value>
				<value>Java Concurrency</value>
			</list>
		</property>
		<property name="hotTopics">
			<map>
				<entry key="java" value="Lambda Expressions" />
				<entry key="functionalLang" value="Scala" />
				<entry key="performance" value="Database Performance" />
			</map>
		</property>
		<property name="programmingTutorial">
			<bean class="com.javarticles.spring.Tutorial">
				<property name="name" value="Scala" />
			</bean>
		</property>
	</bean>
</beans>

In SpringElListBean, we use Spring EL expressions to demonstrate how to access List.

  1. Assign an entire list – we just need to refer to the bean and use ‘.’ to access its list member. Spring expression to access bean’s list member is #{listBean.intList}.
  2. Initialize with a member with list element – We will use java style expression to access the list member. It is similar to the way we have accessed array element. Spring expression to access the list element is #{listBean.intList[1]}
  3. One more example to access the list element – #{tutorial.defaultTopics[1]}, tutorial is the bean ID and defaultTopics is its list member.
  4. Spring EL to check whether an element exists in list – #{tutorial.defaultTopics.contains('Java Core')}. If you note it is similar to the way we check in Java.

SpringELListBean:

package com.javarticles.spring;

import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("springElListBean")
public class SpringElListBean {
    @Value("#{listBean.intList}")
    private List intList;
    
    @Value("#{listBean.intList[1]}")
    private Integer secondListElement;
    
    @Value("#{tutorial.defaultTopics.contains('Java Core')}")
    private boolean defaultTopcsHasJava;
    
    @Value("#{tutorial.defaultTopics[1]}")
    private String freeTopic;
    
    public List getIntList() {
        return intList;
    }

    public Integer getSecondListElement() {
        return secondListElement;
    }

    public boolean defaultTopicsHasJava() {
        return defaultTopcsHasJava;
    }

    public boolean isDefaultTopcsHasJava() {
        return defaultTopcsHasJava;
    }

    public String getFreeTopic() {
        return freeTopic;
    }    
}

We will load the spring context, get the springElListBean and verify whether the members are properly initialized.

SpringElListExample:

package com.javarticles.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringElListExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            System.out.println("SpringElListBean configured using @Value");
            SpringElListBean springElListBean = (SpringElListBean) context.getBean("springElListBean");
            System.out.println("intList: " + springElListBean.getIntList());            
            System.out.println("secondListElement: " + springElListBean.getSecondListElement());
            System.out.println("defaultTopcsHasJava: " + springElListBean.defaultTopicsHasJava());
            System.out.println("freeTopic: " + springElListBean.getFreeTopic());           
        } finally {
            context.close();
        }
    }
}

Output:

SpringElListBean configured using @Value
intList: [1, 3, 5, 7]
secondListElement: 3
defaultTopcsHasJava: true
freeTopic: Java Concurrency

Spring EL Map Example

In our final example, we will see how to use spring EL in Map. Here is a simple Map bean which we will use in our example.

MapBean:

package com.javarticles.spring;

import java.util.Map;

public class MapBean {

    private Map<String, String> mapOfTopics;
  
    private String topicOnPerformance;
    
    private String[] topics;

    public Map<String, String> getMapOfTopics() {
        return mapOfTopics;
    }

    public String getTopicOnPerformance() {
        return topicOnPerformance;
    }

    public String[] getTopics() {
        return topics;
    }

    public void setMapOfTopics(Map<String, String> mapOfTopics) {
        this.mapOfTopics = mapOfTopics;
    }

    public void setTopicOnPerformance(String topicOnPerformance) {
        this.topicOnPerformance = topicOnPerformance;
    }

    public void setTopics(String[] topics) {
        this.topics = topics;
    }           
}

Configure MapBean in spring XML context.

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>

<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.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<context:component-scan base-package="com.javarticles.spring" />

	<bean id="arrayBean" class="com.javarticles.spring.ArrayBean">
		<property name="intArray" value="#{new int[]{1,2,3,4}}" />
	</bean>

	<bean id="listBean" class="com.javarticles.spring.ListBean">
		<property name="intList">
			<list>
				<value>1</value>
				<value>3</value>
				<value>5</value>
				<value>7</value>
			</list>
		</property>
	</bean>

	<bean id="tutorial" class="com.javarticles.spring.Tutorial">
		<property name="name" value="Current Hot Topics" />
		<property name="tutorialPrice" value="300" />
		<property name="defaultTopics">
			<list>
				<value>Java Core</value>
				<value>Java Concurrency</value>
			</list>
		</property>
		<property name="hotTopics">
			<map>
				<entry key="java" value="Lambda Expressions" />
				<entry key="functionalLang" value="Scala" />
				<entry key="performance" value="Database Performance" />
			</map>
		</property>
		<property name="programmingTutorial">
			<bean class="com.javarticles.spring.Tutorial">
				<property name="name" value="Scala" />
			</bean>
		</property>
	</bean>

	<bean id="mapBean" class="com.javarticles.spring.MapBean">
		<property name="mapOfTopics" value="#{tutorial.hotTopics}" />
		<property name="topicOnPerformance" value="#{tutorial.hotTopics['performance']}" />
		<property name="topics" value="#{tutorial.hotTopics.keySet().toArray()}" />
	</bean>
</beans>

Let’s analyze each spring EL used.

  1. Initialize the map member using spring EL – #{tutorial.hotTopics}, assigns hotTopicsMap member from Tutorial bean.
  2. Given a Key, get its value from the Map and initialize the member – #{tutorial.hotTopics['performance']}, gets the map value from Tutorial bean. It uses '.' to reach t o its member and then retrieves the value by passing the key 'performance'
  3. Next, we show how to convert a map’s key set into an array and assign it to the topics member. We use #{tutorial.hotTopics.keySet().toArray(), like other examples, we need to use the bean name and then ‘.’ and the member name to reach to its member. Once we have the member, we can use the allowed member methods on it.

SpringElMapBean:

package com.javarticles.spring;

import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("springElMapBean")
public class SpringElMapBean {

    @Value("#{tutorial.hotTopics}")
    private Map<String, String> mapOfTopics;
  
    @Value("#{tutorial.hotTopics['performance']}")
    private String topicOnPerformance;
    
    @Value("#{tutorial.hotTopics.keySet().toArray()}")
    private String[] topics;

    public Map<String, String> getMapOfTopics() {
        return mapOfTopics;
    }

    public String getTopicOnPerformance() {
        return topicOnPerformance;
    }

    public String[] getTopics() {
        return topics;
    }       
}

SpringElMapExample:

package com.javarticles.spring;

import java.util.Arrays;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringElMapExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            System.out.println("SpringELMapBean configured using @Value");
            SpringElMapBean springElMapBean = (SpringElMapBean) context.getBean("springElMapBean");
            System.out.println("mapOfTopics: " + springElMapBean.getMapOfTopics());
            System.out.println("topics: " + Arrays.asList(springElMapBean.getTopics()));
            System.out.println("topicOnPerformance: " + springElMapBean.getTopicOnPerformance());
            
            System.out.println("MapBean configured in applicationContext.xml using springEl");
            MapBean mapBean = (MapBean) context.getBean("mapBean");
            System.out.println("mapOfTopics: " + mapBean.getMapOfTopics());
            System.out.println("topics: " + Arrays.asList(mapBean.getTopics()));
            System.out.println("topicOnPerformance: " + mapBean.getTopicOnPerformance());            
        } finally {
            context.close();
        }
    }
}

Output:

SpringELMapBean configured using @Value
mapOfTopics: {java=Lambda Expressions, functionalLang=Scala, performance=Database Performance}
topics: [java, functionalLang, performance]
topicOnPerformance: Database Performance
MapBean configured in applicationContext.xml using springEl
mapOfTopics: {java=Lambda Expressions, functionalLang=Scala, performance=Database Performance}
topics: [java, functionalLang, performance]
topicOnPerformance: Database Performance

Download the source code

This was an example about Spring EL expressions accessing values from Array, List and Map.

You can download the source code here: springELArrayListMapExamples.zip
Share.

Comments are closed.