Beginner’s Guide to Spring Expression Language with Spring Boot

Swathi Prasad
2 min readOct 6, 2019

A guide to use Spring Expression Language with @Value annotation.

Image from Flickr

Spring Expression Language (SpEL) is a powerful expression language, which can be used for querying and manipulating an object graph at runtime. SpEL is available via XML or annotation, is evaluated during the bean creation time.

In this article, we will look at some basic examples of SpEL usage in Spring Boot.

Setting up Spring Boot Application

We will create a simple Spring Boot application and create employee.properties file in the resources directory.

employee.names=Petey Cruiser,Anna Sthesia,Paul Molive,Buck Kinnear
employee.type=contract,fulltime,external
employee.age={one:'26', two : '34', three : '32', four: '25'}

Create a class EmployeeConfig as follows:

package com.techshard.spel;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource (name = "employeeProperties", value = "employee.properties")
@ConfigurationProperties
public class EmployeeConfig {
}

Reading Configuration using SpEL and @Value Annotation

We will add some fields to read the configuration from employee.properties using @Value annotation. The @Value annotation can be used for injecting values into fields in Spring-managed beans and it can be applied at the field, constructor or method parameter level.

@Value ("#{'${employee.names}'.split(',')}")
private List<String> employeeNames;

Here, we are using Spring expression language to get a list of employee names. We can manipulate the properties to get the list of values. The field employeeNames will give a list: [Petey Cruiser, Anna Sthesia, Paul Molive, Buck Kinnear].

Suppose we want to get only first entry from a list of employee names, we can write the expression as follows:

@Value ("#{'${employee.names}'.split(',')[0]}")
private String
Swathi Prasad

Software architect and developer living in Germany. Sharing my opinion and what I learn.