Injecting values using XML (SpEL)

We can define the bean in the XML configuration and use SpEL to inject the bean’s properties into the dependent bean.

Following example demonstrates injecting values with XML based configuration 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;

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="#{}" />

I have used the SpEL #{} in referencing the property of the other bean.

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());

The folder structure of the example is shown below in Figure 57.1

Figure 57.1 Figure 57.1

You can download the source code of this example here.

, , ,

No comments yet.

Leave a Reply