How do I call static method using Spring EL?

In this example you will learn how to call static method using Spring EL. The T() operator of the Spring EL can be use to call static method. First, create the following class, NumberGenerator. This class have a single property randomNumber and getter / setter method.

package org.kodejava.example.spring.el;

public class NumberGenerator {
    private int randomNumber;

    public int getRandomNumber() {
        return randomNumber;

    public void setRandomNumber(int randomNumber) {
        this.randomNumber = randomNumber;

Now, create the following spring configuration file and save it in a file called SpELStatic.xml. In this configuration we register a bean called bean of type NumberGenerator. We set its randomNumber property using the value produced by the java.lang.Math.random() static method. For calling a static method we use the Spring EL T() operator, for example #{T(java.lang.Math).random()}.

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

    <bean id="bean" class="org.kodejava.example.spring.el.NumberGenerator">
        <property name="randomNumber"
                  value="#{T(java.lang.Math).random() * 100 + 1}"/>


The program below load the spring configuration and get the NumberGenerator bean to create a randon number.

package org.kodejava.example.spring.el;

import org.springframework.context.ApplicationContext;

public class StaticELDemo {
    public static void main(String[] args) {
        ApplicationContext context =
            new ClassPathXmlApplicationContext("spel-static.xml");

        NumberGenerator number = (NumberGenerator) context.getBean("bean");
        System.out.println("Random number: " + number.getRandomNumber());

And example result you might get when running the program:

Random number: 33

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.