Invoking static methods in SpEL

In this post under Spring SpEL, I will show with example how to invoke static method in SpEL.

In SpEL expression, to inform Spring that we are calling static method of class, we use T operator.

T operator followed by class name within paranthesis informs the Spring to use Class object of the specified class.

So if we say

T(Integer)

We are saying Spring to use Class object of Integer class.

Below is the complete code for your reference.

Main class

1  package spel.package8;
2  
3  import org.springframework.beans.factory.annotation.Value;
4  import org.springframework.context.ApplicationContext;
5  import org.springframework.context.annotation.AnnotationConfigApplicationContext;
6  import org.springframework.context.annotation.ComponentScan;
7  import org.springframework.context.annotation.Configuration;
8  
9  import java.util.List;
10 
11 @Configuration
12 @ComponentScan(basePackages = "spel.package8")
13 public class Example8 {
14     @Value("#{T(Integer).parseInt('7')}")
15     private int value;
16 
17     @Value("#{T(java.util.Collections).emptyList()}")
18     private List<Integer> list;
19 
20     public static void main(String[] args) {
21         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example8.class);
22         Example8 example8 = applicationContext.getBean(Example8.class);
23         System.out.println(example8.value);
24         System.out.println(example8.list.isEmpty());
25     }
26 }

As you can see in the code, I have added two SpEl expressions one for integer variable “value” and other list variable “list”.

In the first expression (at line 14 which is for “value” variable), we are calling static method “parseInt” of “Integer” class.

In the second expression (at line 17 which is for “list” variable), we are calling static method “emptyList” of “Collections” class.

If we compare both the expression, there is a difference in how we identify the class.

In the first case, we are not using fully qualified name of the class whereas in the second case we are using fully qualified name of the class.

If we want to use a class which is under package “java.lang”, we can use just the class name. No need of fully qualified name but if we are using a class outside of package “java.lang”, we have to use
fully qualified name.

In this way we can call class’s static method.

Leave a comment