How do I inject beans, properties and methods using Spring EL?

Using Spring Expression Language (SpEL) we can inject object references or values into a bean dynamically when the bean is created instead of statically defined at development time. In this example you’ll learn how to inject a bean’s property using a property of another bean.

Let start by create two classes, the Student and Grade classes. The student object will have a property to store their grade name which will be obtained from the grade object.

package org.kodejava.example.spring.el;

public class Student {
    private String name;
    private String grade;

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }
}
package org.kodejava.example.spring.el;

public class Grade {
    private String name;
    private String description;

    public Grade() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

Next we create the spring configuration file. In this configuration we have two beans definition, the grade and student bean. We set the name and description property of the grade bean.

We also set the name property of student bean using a string literal. But the grade property value is set to the grade‘s bean name property using the Spring EL, #{grade.name}. The expression tells the spring container to look for a bean whose id is grade, read its name and assign it to student‘s grade.

<?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.xsd">

    <bean id="grade" class="org.kodejava.example.spring.el.Grade">
        <property name="name" value="Beginner"/>
        <property name="description" value="A beginner grade."/>
    </bean>
    <bean id="student" class="org.kodejava.example.spring.el.Student">
        <property name="name" value="Alice"/>
        <property name="grade" value="#{grade.name}"/>
    </bean>

</beans>

And then create the following program to execute the spring container and retrieve the student bean from it.

package org.kodejava.example.spring.el;

import org.kodejava.example.spring.model.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELDemo {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spel-example.xml");

        Student student = (Student) context.getBean("student");
        System.out.println("Name  = " + student.getName());
        System.out.println("Grade = " + student.getGrade());
    }
}

This program will print the following output:

Name  = Alice
Grade = Beginner

How do I wire / inject a null value in Spring?

To wire or inject a null value into a bean we can use the <null> element. The configuration below show you how to do it in the Spring configuration file. You might need to wire a null value for instance when you want to override a value that was autowired into a bean.

As you can see on the configuration below we set the value of property writer in the bean song to a null And we also set a couple null values into the songs property in the album bean.

<?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.xsd">

    <bean id="song" class="org.kodejava.example.spring.collection.Song">
        <property name="title" value="I Saw Her Standing There"/>
        <property name="writer">
            <null/>
        </property>
    </bean>

    <bean id="album" class="org.kodejava.example.spring.collection.Album">
        <property name="title" value="Please Please Me"/>
        <property name="year" value="1963"/>
        <property name="songs">
            <list>
                <ref bean="song"/>
                <null/>
                <null/>
            </list>
        </property>
    </bean>

</beans>

How do I inject collections using props element in Spring?

This time we will demonstrate how to inject a java.util.Properties. This class store a key-value pairs of data where the key and the values are both in string. You can use the <props> element to wire a property collections.

The bean we use in this example is taken from the previous example How do I inject collections using list element in Spring?.

Let’s create the configuration file and call it CollectionProps.xml.

<?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.xsd">

    <bean id="song1" class="org.kodejava.example.spring.collection.Song">
        <property name="title" value="I Saw Her Standing There" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song2" class="org.kodejava.example.spring.collection.Song">
        <property name="title" value="Misery" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song3" class="org.kodejava.example.spring.collection.Song">
        <property name="title" value="Anna (Go to Him)" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="publisher" class="org.kodejava.example.spring.collection.Publisher">
        <property name="name" value="EMI Studios"/>
    </bean>

    <bean id="album" class="org.kodejava.example.spring.collection.Album">
        <property name="title" value="Please Please Me"/>
        <property name="year" value="1963"/>
        <property name="props">
            <props>
                <prop key="color">Black</prop>
                <prop key="type">CD</prop>
                <prop key="duration">1 Hour</prop>
            </props>
        </property>
    </bean>

</beans>

To wire property collections we use the <props> element. This element can have many <prop> in it. The key of the property defined by the key attribute of this element. The value of the property is set in the body of this element.

As usual let’s create a simple program to run it:

package org.kodejava.example.spring.collection;

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

public class DemoProps {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[]{"collection-props.xml"});

        Album album = (Album) context.getBean("album");
        System.out.println("Album = " + album);
    }
}

When you run it, it will produce the following output:

Album = Album{title='Please Please Me', year=1963, songs=[], publisher={}, props={color=Black, type=CD, duration=1 Hour}}

How do I inject collections using map element in Spring?

In this example you will see how to wire map collections. For this purpose we can use the <map> element in the Spring configuration file. This element declares the java.util.Map. We will reuse the bean that we use in the previous example How do I inject collections using list element in Spring?.

The <map> element can have many <entry> element with the key and value-ref attribute.

Here is the configuration example:

<?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.xsd">

    <bean id="song1" class="org.kodejava.example.spring.collection.Song">
        <property name="title" value="I Saw Her Standing There" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song2" class="org.kodejava.example.spring.collection.Song">
        <property name="title" value="Misery" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song3" class="org.kodejava.example.spring.collection.Song">
        <property name="title" value="Anna (Go to Him)" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="publisher" class="org.kodejava.example.spring.collection.Publisher">
        <property name="name" value="EMI Studios"/>
    </bean>

    <bean id="album" class="org.kodejava.example.spring.collection.Album">
        <property name="title" value="Please Please Me"/>
        <property name="year" value="1963"/>
        <property name="publisher">
            <map>
                <entry key="publisher" value-ref="publisher"/>
            </map>
        </property>
    </bean>

</beans>

The <map> element can have many <entry> elements. We can use the key attribute to use a string as its key. If you want the key to be a reference to other bean in the Spring context you can use the key-ref instead.

The value-ref is used to set the value to refer to another bean. If the value is a simple value such as string you can use the value attribute.

To run it create the following program:

package org.kodejava.example.spring.collection;

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

public class DemoMap {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[]{"collection-map.xml"});

        Album album = (Album) context.getBean("album");
        System.out.println("Album = " + album);
    }
}

And here what you’ll get on the console:

Album = Album{title='Please Please Me', year=1963, songs=[], publisher={publisher=Publisher{name=EMI Studios}}, props={}}

How do I inject collections using set element in Spring?

In this example you will see how to use the <set> element to wire a collection property of a bean. We will reuse the bean that we use in the previous example How do I inject collections using list element in Spring?.

The Album bean have a songs property that have a type of java.util.List. The <set> element does not have to be used with java.util.Set. It can be used to wire a java.util.List collection. It just mean the it cannot contains duplicate values in it, so the collection will only contains a unique values.

Here how we configure our Spring context:

<?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.xsd">

    <bean id="song1" class="org.kodejava.example.spring.collection.Song">
        <property name="title" value="I Saw Her Standing There" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song2" class="org.kodejava.example.spring.collection.Song">
        <property name="title" value="Misery" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song3" class="org.kodejava.example.spring.collection.Song">
        <property name="title" value="Anna (Go to Him)" />
        <property name="writer" value="Beatles" />
    </bean>


    <bean id="album" class="org.kodejava.example.spring.collection.Album">
        <property name="title" value="Please Please Me"/>
        <property name="year" value="1963"/>
        <property name="songs">
            <set>
                <ref bean="song1"/>
                <ref bean="song1"/>
                <ref bean="song1"/>
            </set>
        </property>
    </bean>

</beans>

The <set> configuration can bee seen in the album bean configuration. We set the songs property. Within this property element we use the <set> element. And then using the <ref> element we add some bean into the collection.

Create the following code to run it:

package org.kodejava.example.spring.collection;

public class Song {
    private String title;
    private String writer;

    public Song() {
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setWriter(String writer) {
        this.writer = writer;
    }

    @Override
    public String toString() {
        return "Song{" +
            "title='" + title + '\'' +
            ", writer='" + writer + '\'' +
            '}';
    }
}
package org.kodejava.example.spring.collection;

public class Publisher {
    private String name;

    public Publisher() {
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Publisher{" +
                "name=" + name +
                '}';
    }
}
package org.kodejava.example.spring.collection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class Album {
    private String title;
    private int year;
    private List<Song> songs = new ArrayList<>();
    private Map<String, Publisher> publisher = new HashMap<>();
    private Properties props = new Properties();

    public Album() {
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public void setSongs(List<Song> songs) {
        this.songs = songs;
    }

    public void setPublisher(Map<String, Publisher> publisher) {
        this.publisher = publisher;
    }

    public void setProps(Properties props) {
        this.props = props;
    }

    @Override
    public String toString() {
        return "Album{" +
            "title='" + title + '\'' +
            ", year=" + year +
            ", songs=" + songs +
            ", publisher=" + publisher +
            ", props=" + props +
            '}';
    }
}
package org.kodejava.example.spring.collection;

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

public class DemoSet {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[]{"collection-set.xml"});

        Album album = (Album) context.getBean("album");
        System.out.println("Album = " + album);
    }
}

You’ll see the following output in the screen. As you can see, although we set three beans into the songs property, the Album bean only contain a single song. This is because we use the <set> element to wire the collection. It does not allow duplicate values.

Album = Album{title='Please Please Me', year=1963, songs=[Song{title='I Saw Her Standing There', writer='Beatles'}], publisher={}, props={}}

How do I inject collections using list element in Spring?

The following example show you how to use the <list> element to wire collections property. We can use it to wire property of either arrays or some implementation of java.util.Collection such as java.util.ArrayList.

For this example we will create a bean called Album that have a collection of Song beans in it. So here is our bean classes.

package org.kodejava.example.spring.collection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class Album {
    private String title;
    private int year;
    private List<Song> songs = new ArrayList<>();
    private Map<String, Publisher> publisher = new HashMap<>();
    private Properties props = new Properties();

    public Album() {
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public void setSongs(List<Song> songs) {
        this.songs = songs;
    }

    public void setPublisher(Map<String, Publisher> publisher) {
        this.publisher = publisher;
    }

    public void setProps(Properties props) {
        this.props = props;
    }

    @Override
    public String toString() {
        return "Album{" +
            "title='" + title + '\'' +
            ", year=" + year +
            ", songs=" + songs +
            ", publisher=" + publisher +
            ", props=" + props +
            '}';
    }
}
package org.kodejava.example.spring.collection;

public class Song {
    private String title;
    private String writer;

    public Song() {
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setWriter(String writer) {
        this.writer = writer;
    }

    @Override
    public String toString() {
        return "Song{" +
            "title='" + title + '\'' +
            ", writer='" + writer + '\'' +
            '}';
    }
}
package org.kodejava.example.spring.collection;

public class Publisher {
    private String name;

    public Publisher() {
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Publisher{" +
                "name=" + name +
                '}';
    }
}

Here is the Spring configuration file, CollectionList.xml.

<?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.xsd">

    <bean id="song1" class="org.kodejava.example.spring.collection.Song">
        <property name="title" value="I Saw Her Standing There" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song2" class="org.kodejava.example.spring.collection.Song">
        <property name="title" value="Misery" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song3" class="org.kodejava.example.spring.collection.Song">
        <property name="title" value="Anna (Go to Him)" />
        <property name="writer" value="Beatles" />
    </bean>


    <bean id="album" class="org.kodejava.example.spring.collection.Album">
        <property name="title" value="Please Please Me"/>
        <property name="year" value="1963"/>
        <property name="songs">
            <list>
                <ref bean="song1"/>
                <ref bean="song2"/>
                <ref bean="song3"/>
            </list>
        </property>
    </bean>

</beans>

The part of the configuration that wire the songs collection is inside the album bean. You can see that we have a property name songs. This property have a <list> element that contains a couple <ref> elements referring to some Song type beans.

Now let’s run it with the following code:

package org.kodejava.example.spring.collection;

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

public class DemoList {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[]{"collection-list.xml"});

        Album album = (Album) context.getBean("album");
        System.out.println("Album = " + album);
    }
}

You’ll see the following output when you run the program:

Album = Album{title='Please Please Me', year=1963, songs=[Song{title='I Saw Her Standing There', writer='Beatles'}, Song{title='Misery', writer='Beatles'}, Song{title='Anna (Go to Him)', writer='Beatles'}], publisher={}, props={}}

How do I inject collections properties in Spring?

Beside injecting a simple value (using the value attribute) and a reference to other bean (using the ref attribute). We can also inject collections properties into a bean.

Spring provides four ways to inject collections. There are <list> and <set> that can be used to inject arrays or any implementation of java.util.Collection. The <map> that can be used to inject property of type java.util.Map. And the <props> can be used to inject property of type java.util.Properties.

Here is a table that summarize the collection configuration support in Spring.

Collection Element Description
<list> Wiring a list of values, where the values might have duplicates.
<set> Wiring a set of values, where the values can not have duplicates.
<map> Wiring a key-value pairs collection, where the key and value can be any type
<props> Wiring a key-value pairs property, where the key and value are both type of String

You can see the following example on how to use each type of this collection configuration:

How do I inject into bean properties?

A bean usually have some private properties that can be accessed through a pair of accessor methods, the setters and getters. This setters, the setXXX() method can be used by Spring framework to configure the beans.

This method of injecting beans property through their setter methods is called the setter injection. The following example will show you how to do it.

Below is our DrawingBean that have colour and shape properties. In the example we will inject both of the properties using their respective setter method. This configuration is done in the Spring application configuration file.

package org.kodejava.example.spring.inject;

public class DrawingBean {
    private String colour;
    private Shape shape;

    public DrawingBean() {
    }

    public void drawShape() {
        getShape().draw();
        System.out.printf("The colour is %s.", getColour());
    }

    public String getColour() {
        return colour;
    }

    public void setColour(String colour) {
        this.colour = colour;
    }

    public Shape getShape() {
        return shape;
    }

    public void setShape(Shape shape) {
        this.shape = shape;
    }
}

We can inject a simple value into a bean, such as string, number, etc. We can also inject a reference to another bean. Here we define an example of other bean, the Rectangle bean that we will inject into the DrawingBean.

package org.kodejava.example.spring.inject;

public interface Shape {
    /**
     * Draw a shape.
     */
    void draw();
}
package org.kodejava.example.spring.inject;

public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle.");
    }
}

Let’s create the Spring application configuration file that will register our beans into the Spring context. After that we just create a simple program to execute it.

<?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.xsd">

    <bean id="rectangle" class="org.kodejava.example.spring.inject.Rectangle"/>

    <bean id="drawingBean" class="org.kodejava.example.spring.inject.DrawingBean">
        <property name="colour" value="Red"/>
        <property name="shape" ref="rectangle"/>
    </bean>

</beans>

In the configuration file above you can see that we use the property element to set a bean’s property. The name attribute is referring to the bean’s setter methods name, exclude the set prefix.

The value attribute of the property element is used to inject a simple value, such as string, int, etc. For injecting a reference to another bean we use the ref attribute instead.

package org.kodejava.example.spring.inject;

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

public class DrawingBeanDemo {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[]{"drawing-bean.xml"});
        DrawingBean bean = (DrawingBean) context.getBean("drawingBean");
        bean.drawShape();
    }
}

Here are the output of our example:

Drawing a rectangle.
The colour is Red.

How do I inject a bean through constructors?

The following example demonstrate how we can inject a bean through their constructors. We will create a couple interfaces and classes for this purpose. First we will create the Singer interface and the Instrument interface. The Singer interface define a single method call sing() that will enable the implementation to sing a song.

The second interface, Instrument also define a single method call play(). This method will allow the implementation to play some instrument. After defining our example interface we create an implementation for each of them. The class will be called the AnySinger and Piano.

Here are the code that we have to code so far:

package org.kodejava.example.spring.singer;

public interface Singer {
    /**
     * Sing a song.
     */
    void sing();
}
package org.kodejava.example.spring.singer;

public interface Instrument {
    /**
     * Play an instrument.
     */
    void play();
}
package org.kodejava.example.spring.singer;

public class AnySinger implements Singer {
    private String song = "Nana nana nana";
    private Instrument instrument = null;

    public AnySinger() {
    }

    /**
     * A constructor to create singer to sing a specific song.
     *
     * @param song the song title to sing.
     */
    public AnySinger(String song) {
        this.song = song;
    }

    /**
     * A constructor to create singer to sing a song while playing
     * an instrument.
     *
     * @param song the song title to sing.
     * @param instrument the instrument to play.
     */
    public AnySinger(String song, Instrument instrument) {
        this.song = song;
        this.instrument = instrument;
    }

    @Override
    public void sing() {
        System.out.println("Singing " + song);
        if (instrument != null) {
            instrument.play();
        }
    }
}
package org.kodejava.example.spring.singer;

public class Piano implements Instrument {

    @Override
    public void play() {
        System.out.println("Playing the Piano");
    }
}

We have created the classes that we need for our program to work. The next step is to create our spring configuration file. This will configure our bean in the spring container and wire all the dependency required by the bean.

<?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.xsd">

    <bean id="piano" class="org.kodejava.example.spring.singer.Piano"/>

    <bean id="singer" class="org.kodejava.example.spring.singer.AnySinger">
        <constructor-arg value="Dust in The Wind"/>
        <constructor-arg ref="piano"/>
    </bean>

</beans>

In the spring configuration we declare two beans. The first bean is the piano bean, which is a type of instrument. The main object of our example is the singer bean. To create the singer we use a constructor injector to inject some values or object reference for the bean to use.

In the singer bean we use the &lt;constructor-arg/&gt; element to inject dependency for the object. The value attribute can be use for passing a string or other primitive value. To pass an object reference we need to use the ref attribute.

Finally, we’ll create a simple program to run our constructed spring application. The code will include the process of loading our spring container, obtaining the bean from the container. Let’s see our singer in action.

package org.kodejava.example.spring.singer;

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

public class SingerDemo {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("singer.xml");

        Singer singer = (Singer) context.getBean("singer");
        singer.sing();
    }
}