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.spel;

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="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

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

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

package org.kodejava.example.spring.spel;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class StaticELDemo {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("SpELStatic.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
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply