SpEL

Spring Expression Language (SpEL) supports parsing and executing expressions with the help of @Value annotation.

If we use an expression within @Value annotation, Spring IoC container will evaluate it and that expression will return a value. It supports, both primitive types, as well as collections inside the expression.

Expression can be a combination of Classes, Variables, methods, constructors and objects. Expression will always go into @Value annotation.

General syntax :

@Value(“#{<expression>}”)

Examples :
@Value("#{60+40}")
@Value("#{5>6?1:0}")

We can use static methods, object methods, or variables, etc for these expressions.

Using Static methods :

Syntax :

T(class).method(param)

Example :

@Value("#{T(java.lang.Math).abs(-99)}")
private int number;

Creating objects & Accessing Static variables :

T(class).<static_field>

@Value("#{new Integer(10)}")
private int id;

@Value("#{T(java.lang.Integer).MIN_VALUE}")
private int minValue;

 

Creating String type :

Use single quotes ‘ ‘ for enclosing string value.

Examples :

@Value("#{'Raghu'}")
private String name;

// calling String methods
@Value("#{'Raghu'.toUpperCase()}")
private String name;

// new String object
@Value("#{new java.lang.String('Raghu')}")
private String name;