Home Tutorial Spring Spring3 Web Calling Static Methods Using SpEL

 
 

Calling Static Methods Using SpEL
Posted on: April 7, 2011 at 12:00 AM
Advertisement
In this tutorial you will learn how to call Static Methods Using SpEL

Calling Static Method Using SpEL

Spring 3 provides powerful Expression Language which can be used to wire values into beans properties by calling static method of any bean using SpEL's T() operator.

Lets take an example to demonstrate how SpEL is used to wire value by calling static  method.

MyClass.java: The MyClass class contains property named "random" which is of String type.

package spel.callingstaticmethodsusingSpEL;

public class MyClass
{
private String random;

public void setRandom(String random) {
this.random = random;
}
public String getRandom() {
return random;
}
}

spring-beans.xml: We will see how to use static method random() of java.util.Math class to wire random property of the MyClass class using T() operator of Spring expression Language. This operator takes fully qualified class name.

<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-2.5.xsd">

<bean id="myClass" class="spel.callingstaticmethodsusingSpEL.MyClass">
<property name="random" value="#{T(java.lang.Math).random()}"/>
</bean>

</beans>

AppMain.java: This class loads the context configuration file spring-beans-list.xml from the class path.

package spel.callingstaticmethodsusingSpEL;

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

import spel.callingstaticmethodsusingSpEL.MyClass;

public class AppMain{
public static void main( String[] args ){
ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] {"spel\\callingstaticmethodsusingSpEL\\spring-beans-list.xml"});
MyClass myObj = (MyClass)appContext.getBean("myClass");

System.out.println("-------------------------------------");
System.out.println("Random Value: "+myObj.getRandom());
System.out.println("-------------------------------------");
}
}

The output of the above program will be as below:

-------------------------------------
Random Value: 0.6188206590561351
-------------------------------------

Download Select Source Code

Advertisement

Related Tags for Calling Static Methods Using SpEL:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 7, 2011

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com