Invoke method using Spring Expression Language

You can also invoke a method using Spring Expression Language.

Following example demonstrates how to invoke method using Spring Expression Language.

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml

  <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.1.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>3.1.1.RELEASE</version>
    </dependency> 
  </dependencies>

1. POJO

Create Instrument Class as following

package com.kruders.bean;

public class Instrument {
	private String instrument;
	private String song;
	public String getInstrument() {
		return instrument;
	}
	public void setInstrument(String instrument) {
		this.instrument = instrument;
	}
	public String getSong() {
		return song;
	}
	public void setSong(String song) {
		this.song = song;
	}
	
	public String currentSong() {
		return "Titanic";
	}
}

2. Configuration

Create Spring-Bean.xml and write the following code

<?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="kunnal" class="com.kruders.bean.Instrument">
        <property name="instrument" value="Guitar" />
        <property name="song" value="Bailamos" />
    </bean>
    
    <bean id="puneet" class="com.kruders.bean.Instrument">
        <property name="instrument" value="Keyboard" />
        <property name="song" value="#{kunnal.currentSong()}" />
    </bean>
</beans>

I have used the SpEL #{kunnal.currentSong()} to invoke method and inject returned value into property.

3. Run Program

Create Main.java class and run it as Java Application

package com.kruders.core;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.kruders.bean.Instrument;
 
public class Main {
    public static void main(String[] args) {
    	ApplicationContext context = new ClassPathXmlApplicationContext(
                "Spring-Bean.xml");
        Instrument instrument = (Instrument) context.getBean("puneet");
        System.out.println("Instrument " + instrument.getInstrument());
        System.out.println("Song " + instrument.getSong());
    }
 
}


, , ,

No comments yet.

Leave a Reply