Spring spel method invocation example

Spring SpEL method invocation:

Spring spel provides the facility of method invocation i.e. execute method and inject the method returned value into property.

Syntax:

#{beanName.methodName}

Example:

Address.java

import org.springframework.stereotype.Component;

@Component("studentClassBean")
public class StudentClass {
	public String getClassName(){
		return "MCA Final";
	}
}

Student.java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("studentBean")
public class Student {
	@Value("Jai")
	private String name;	
	
	@Value("#{studentClassBean.className}")
	private String className;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}	
}

applicationContext.xml



 


Test.java

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

/**
 * Spring SPEL method invocation example.
 * @author W3schools360
 */
public class Test {
 public static void main(String args[]){	
   //Get application context object.
   ApplicationContext context = 
     new ClassPathXmlApplicationContext("applicationContext.xml");
	
   //Get studentBean.
   Student student = (Student) context.getBean("studentBean");
	
   //Print student properties.
   System.out.println("Name: "+student.getName()); 
   System.out.println("Street: "+student.getClassName()); 
 }
}

Output:

Name: Jai
Street: MCA Final

 
Download this example.