In this example you will learn how to call static method using Spring EL. The T()
operator of the Spring EL can be used to call static method. First, create the following class, NumberGenerator
. This class has a single property randomNumber
and getter / setter method.
package org.kodejava.spring.core.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="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.xsd">
<bean id="bean" class="org.kodejava.spring.core.el.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 random number.
package org.kodejava.spring.core.el;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class StaticELDemo {
public static void main(String[] args) {
try (ClassPathXmlApplicationContext 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
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.3.23</version>
</dependency>
</dependencies>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024