Introduction to Spring Expression Language(SPEL)

I think we have enough features up to now in spring, but spring is not settling down it is updating day-by-day with packs of advanced features to let its users feel spring is simple. Now we gonna see one of those feature SPEL(spring expression language). Lets have an working example of spring project using SPEL. has two java beans(setters) which we will need to set those values from beans.xml by using SPEL.

package com.sourceforopensource.pojos;

public class Robot {

private String id = "Default robot";
private String speech = "hello";

public void speak() {
System.out.println(id + ": " + speech);

public void setId(String id) { = id;

public void setSpeech(String speech) {
this.speech = speech;


This will return a random text when we call the getText() method.

package com.sourceforopensource.pojos;

import java.util.Random;

public class RandomText {
 private static String[] texts = {
 "I'll be back",
 "Get out!",
 "I want your clothes, boots and motorcycle.",
 public String getText() {
 Random random = new Random();
 return texts[random.nextInt(texts.length)];

To enable expression language #{write expressions here} is used. Expressions
//are many types like arthematic expressions and mathod calling and etc..


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
 xmlns:xsi="" xmlns:p=""

 <bean id="robot" class="com.sourceforopensource.pojos.Robot">
 <property name="id" value="#{randomText.text?.length()}"></property>//here the ? will prevent accessing the null value.
 <property name="speech" value="#{'random text: ' + randomText.getText()}"></property>

 <bean id="randomText" class="com.sourceforopensource.pojos.RandomText">

package com.sourceforopensource.pojos;

import org.springframework.context.ApplicationContext;

public class App {

 public static void main(String[] args) {
 ApplicationContext context = new ClassPathXmlApplicationContext("com/sourceforopensource/beans/beans.xml");
 Robot robot = (Robot)context.getBean("robot");



outputs are random texts.

Balakrishna Pendyala

Author: Balakrishna Pendyala

Balakrishna is a Software Engineer working in Media Streaming Domain, and also worked on Banking and Health Care domains. His areas of interest include Object Oriented Design, SOLID Design principles, Restful Web Services and Open Source softwares including Spring, Spring Boot, and Hibernate.

If you found an error, highlight it and press Shift + Enter or click here to inform us.

Leave a Reply

Your email address will not be published. Required fields are marked *