Spring EL Property Examples

0

In this article, we demonstrate the usage of spring expression language in accessing properties. We will show you how to use Spring EL to navigate the property references with several examples.

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 Accessing Property Example

To understand Spring EL property expressions we will use a Tutorial object. It contains an Integer(tutorialPrice), a static member (MAIN_TOPIC), a List, a Tutorial(programmingTutorial) and a Map/code> members.

Tutorial:

package com.javarticles.spring;

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

public class Tutorial {
    public static final String MAIN_TOPIC = "SpringEL";
    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(String name, List topicsList){
        this.name = name;
        this.defaultTopics = topicsList;
    }
    
    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 Tutorial bean in applicationContext.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="currentTopics" 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>

Using Spring EL expressions we will navigating the property references. We just need to use the Tutorial bean configured and then use a period to navigate through the nested properties.

Let’s go through each expression.

  1. #{currentTopics.tutorialPrice * 2}currentTopics is the configured bean. We then use a dot to access the tutorial price. We can even use matematical operators to work on the integer. We have doubled the price here.
  2. #{currentTopics.programmingTutorial.name} – Again using dot, we have accessed the Tutorial type and then again using dot, accessed the name of the tutorial.
  3. #{currentTopics.defaultTopics.size() – Here we get the number of default topics taught
  4. #{T(com.javarticles.spring.Tutorial).MAIN_TOPIC – using T(<class name>) we can refer to the class and then using dot the static members
  5. #{new com.javarticles.spring.Tutorial('Spring Tutorials', {'Spring EL Property', 'Spring Context'})} – Here we have used new and instantiated a Tutorial object. It takes a name and a list.

SpringElPropertyBean:

package com.javarticles.spring;

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

@Component
public class SpringElPropertyBean {
    @Value("#{currentTopics.tutorialPrice * 2}")
    private Integer intProperty;

    @Value("#{currentTopics.programmingTutorial.name}")
    private String programmingTutorial;
    
    @Value("#{currentTopics.defaultTopics.size()}")
    private int topicsCount;
    
    @Value("#{T(com.javarticles.spring.Tutorial).MAIN_TOPIC}")
    private String mainTopic;
    
    @Value("#{new com.javarticles.spring.Tutorial('Spring Tutorials', {'Spring EL Property', 'Spring Context'})}")
    private Tutorial tutorial;

    public Integer getIntProperty() {
        return intProperty;
    }

    public String getProgrammingTutorial() {
        return programmingTutorial;
    }

    public int getTopicsCount() {
        return topicsCount;
    }

    public String getMainTopic() {
        return mainTopic;
    }

    public Tutorial getTutorial() {
        return tutorial;
    }          
}

Test Spring EL Property Expressions

Let’s test the Spring EL expressions now.

SpringElPropertyExample:

package com.javarticles.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringElPropertyExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            System.out.println("SpringElPropertyBean configured using @Value");
            SpringElPropertyBean springElPropertyBean = (SpringElPropertyBean) context.getBean("springElPropertyBean");
            System.out.println("intProperty: " + springElPropertyBean.getIntProperty());
            System.out.println("programmingTutorial: " + springElPropertyBean.getProgrammingTutorial());
            System.out.println("topicsCount: " + springElPropertyBean.getTopicsCount());
            System.out.println("mainTopic: " + springElPropertyBean.getMainTopic());
            System.out.println("tutorial: " + springElPropertyBean.getTutorial());
        } finally {
            context.close();
        }
    }
}

Output:

SpringElPropertyBean configured using @Value
intProperty: 600
programmingTutorial: Scala
topicsCount: 2
mainTopic: SpringEL
tutorial: Spring Tutorials[Spring EL Property, Spring Context]

Download the source code

This was an example about accessing properties using Spring EL.

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

Comments are closed.