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
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.w3schools.business" /> </beans> |
Test.java
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Spring SPEL method invocation example. * @author w3schools */ 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 |