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



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

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

3. Run Program

Create class and run it as Java Application

package com.kruders.core;

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

, , ,

No comments yet.

Leave a Reply