How do I compare values in Spring EL?

In Spring EL you can compare two values to know if they are equals, is greater or smaller than the other value.  For these kind of comparison below are the list of operators supported by Spring EL, as expected it supports the same operators as in the Java programming language.

The Spring Expression Language comparison operators includes:

Symbol Textual Description
== eq Double-equal operator to compare two values for equality.
< lt Less-than operator to compare if a value is smaller than the other value.
> gt Greater-than operator to compare if a value is greater than the other value.
<= le Less-than-or-equal operator to compare if a value is smaller or equals to another value.
>= ge Greater-than-or-equal operator to compare if a value is greater or equals to another value.

For example you can use the double-equal operator like the following XML configuration:

<property name="empty" value="#{myGlass.volume == 0}"/>

It means that we are going to set the empty property to be either a boolean true or false if the value of myGlass.volume is equal to 0 or not. The double-equal symbol is not a problem when use in the XML document. But you will understand right away that you can’t use the less-than (<) or greater-than (>) symbol in XML, because the characters is used to define the XML document it self.

To make it work we must use the textual version of these operators. For example you will use the lt instead of < symbol or gt instead of the > symbol as can be see in the table above. Now let’s see an example in the spring configuration file.

<?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="myGlass" class="org.kodejava.example.spring.el.MyGlass">
        <constructor-arg name="volume" value="5"/>
        <constructor-arg name="maxVolume" value="10"/>
        <property name="empty" value="#{myGlass.volume == 0}"/>
        <property name="halfEmpty" value="#{(myGlass.maxVolume / 2) le myGlass.volume}"/>
    </bean>

</beans>

In the above configuration we have a bean called myGlass. We instantiate it with two constructor values, the volume was set to 5 and the maxVolume was set to 10. To set the value of the empty and halfEmpty property we use the double-equal and less-than-equal operator to check the value of the volume and maxVolume properties.

After you have the spring configuration, let’s create the MyGlass bean and an application to run the configuration file. The bean is just a simple class with some properties and a collections of getters and setters.

package org.kodejava.example.spring.el;

public class MyGlass {
    private boolean empty;
    private boolean halfEmpty;
    private int volume;
    private int maxVolume;

    public MyGlass() {
    }

    public MyGlass(int volume, int maxVolume) {
        this.volume = volume;
        this.maxVolume = maxVolume;
    }

    public boolean isEmpty() {
        return empty;
    }

    public void setEmpty(boolean empty) {
        this.empty = empty;
    }

    public boolean isHalfEmpty() {
        return halfEmpty;
    }

    public void setHalfEmpty(boolean halfEmpty) {
        this.halfEmpty = halfEmpty;
    }

    public int getVolume() {
        return volume;
    }

    public void setVolume(int volume) {
        this.volume = volume;
    }

    public int getMaxVolume() {
        return maxVolume;
    }

    public void setMaxVolume(int maxVolume) {
        this.maxVolume = maxVolume;
    }
}

To run the spring configuration above you can create the SpELCompareValue class below.

package org.kodejava.example.spring.el;

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

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

        MyGlass glass = (MyGlass) context.getBean("myGlass");
        System.out.println("glass.getVolume()   = " + glass.getVolume());
        System.out.println("glass.isEmpty()     = " + glass.isEmpty());
        System.out.println("glass.isHalfEmpty() = " + glass.isHalfEmpty());
    }
}

And when you executed the code above you will get the following output:

glass.getVolume()   = 5
glass.isEmpty()     = false
glass.isHalfEmpty() = true

How do I access static methods or constants in Spring EL?

In this examples you will learn how to access class-scoped methods or constants using Spring Expression Language. To access a class-scoped methods or constants you will need to use the T() operator of the Spring EL, for example T(java.lang.Math). This operator will give us the access to static methods and constants on a given class. As an example we can access the Math.PI in Spring EL like T(java.lang.Math).PI.

Just like accessing the static constants we can also access a static method in the same way. For example we can call the Math.random() method in Spring EL like this T(java.lang.Math).random().

Now let’s see how we do these inside a spring configuration file. In this configuration we create a bean called myBean that have properties such as randomNumber, pi and name.

<?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="myBean" class="org.kodejava.example.spring.el.MyOtherBean">
        <property name="randomNumber" value="#{T(java.lang.Math).random()}"/>
        <property name="pi" value="#{T(java.lang.Math).PI}"/>
        <property name="name" value="#{T(org.kodejava.example.spring.el.MyOtherBean).BEAN_NAME}"/>
    </bean>

</beans>

Here are out bean class and an application class that run the spring configuration for the demo.

package org.kodejava.example.spring.el;

public class MyOtherBean {
    public static final String BEAN_NAME = "MyOtherBean";

    private String randomNumber;
    private String pi;
    private String name;

    public void setRandomNumber(String randomNumber) {
        this.randomNumber = randomNumber;
    }

    public String getRandomNumber() {
        return randomNumber;
    }

    public void setPi(String pi) {
        this.pi = pi;
    }

    public String getPi() {
        return pi;
    }

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

    public String getName() {
        return name;
    }
}
package org.kodejava.example.spring.el;

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

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

        MyOtherBean bean = (MyOtherBean) context.getBean("myBean");
        System.out.println("bean.getRandomNumber() = " + bean.getRandomNumber());
        System.out.println("bean.getPi()           = " + bean.getPi());
        System.out.println("bean.getName()         = " + bean.getName());
    }
}

When executing the program you will get the following result as the output:

bean.getRandomNumber() = 0.7173165965231882
bean.getPi()           = 3.141592653589793
bean.getName()         = MyOtherBean

How do I do math operations using Spring EL?

As we know that the simplest value that can be expressed in the Spring EL is a literal value such as number. Further more we can also do math operations using the Spring EL. The spring configuration below show you how can do math operations using the Spring Expression Language. These operations includes:

  • Add operation (+)
  • Subtract operation (-)
  • Multiply operation (*)
  • Divide operations (/)
  • Modulo operation (%)
  • Power operation (^)
<?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="myBean" class="org.kodejava.example.spring.el.MyBean">
        <property name="total" value="#{50 + 50}"/>
        <property name="length" value="#{100 - 10}"/>
        <property name="size" value="#{10 * 10}"/>
        <property name="reminder" value="#{10 % 3}"/>
        <property name="distance" value="#{1000 / 10}"/>
        <property name="power" value="#{2 ^ 10}"/>
    </bean>

</beans>

The configuration above requires a bean / pojo called MyBean. It’s a simple class with some fields and getters and setters. Followed later by a simple class called SpELMathOperationDemo that demonstrate the Spring EL math operations.

package org.kodejava.example.spring.el;

public class MyBean {
    private int total;
    private int length;
    private int size;
    private float distance;
    private int reminder;
    private int power;

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public float getDistance() {
        return distance;
    }

    public void setDistance(float distance) {
        this.distance = distance;
    }

    public int getReminder() {
        return reminder;
    }

    public void setReminder(int reminder) {
        this.reminder = reminder;
    }

    public int getPower() {
        return power;
    }

    public void setPower(int power) {
        this.power = power;
    }
}
package org.kodejava.example.spring.el;

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

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

        MyBean bean = (MyBean) context.getBean("myBean");
        System.out.println("bean.getTotal()    = " + bean.getTotal());
        System.out.println("bean.getLength()   = " + bean.getLength());
        System.out.println("bean.getSize()     = " + bean.getSize());
        System.out.println("bean.getReminder() = " + bean.getReminder());
        System.out.println("bean.getDistance() = " + bean.getDistance());
        System.out.println("bean.getPower()    = " + bean.getPower());
    }
}

And this are the output printed out by the code snippet:

bean.getTotal()    = 100
bean.getLength()   = 90
bean.getSize()     = 100
bean.getReminder() = 1
bean.getDistance() = 100.0
bean.getPower()    = 1024

How do I call static method using Spring EL?

In this example you will learn how to call static method using Spring EL. The T() operator of the Spring EL can be use to call static method. First, create the following class, NumberGenerator. This class have a single property randomNumber and getter / setter method.

package org.kodejava.example.spring.el;

public class NumberGenerator {
    private int randomNumber;

    public int getRandomNumber() {
        return randomNumber;
    }

    public void setRandomNumber(int randomNumber) {
        this.randomNumber = randomNumber;
    }
}

Now, create the following spring configuration file and save it in a file called SpELStatic.xml. In this configuration we register a bean called bean of type NumberGenerator. We set its randomNumber property using the value produced by the java.lang.Math.random() static method. For calling a static method we use the Spring EL T() operator, for example #{T(java.lang.Math).random()}.

<?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="bean" class="org.kodejava.example.spring.el.NumberGenerator">
        <property name="randomNumber"
                  value="#{T(java.lang.Math).random() * 100 + 1}"/>
    </bean>

</beans>

The program below load the spring configuration and get the NumberGenerator bean to create a randon number.

package org.kodejava.example.spring.el;

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

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

        NumberGenerator number = (NumberGenerator) context.getBean("bean");
        System.out.println("Random number: " + number.getRandomNumber());
    }
}

And example result you might get when running the program:

Random number: 33

How do I handle or avoid null value in Spring EL?

In this example you will learn how to avoid a null value, which causing a NullPointerException thrown in a Spring EL expression. To avoid this from happening we can use the null-safe accessor, using the ?. operator.

We are using the previous example, How do I inject bean’s property using Spring EL? classes, which are the Student class and the Grade class. What we need is to create a new spring configuration file to demonstrate this feature. So, here is the configuration file:

<?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="student" class="org.kodejava.example.spring.el.Student">
        <property name="name" value="Alice"/>
        <property name="grade" value="#{grade.getName()?.toUpperCase()}"/>
    </bean>

    <bean id="grade" class="org.kodejava.example.spring.el.Grade">
        <property name="name">
            <null/>
        </property>
        <property name="description" value="A beginner grade."/>
    </bean>

</beans>

The use of null-safe accessor can be seen on the student bean’s grade property. We are calling the grade.getName() method and convert it to uppercase. We deliberately set the grade.name property to null. Calling toUpperCase on a null value will throw the NullPointerException. But because we are using the null-safe accessor the exception is not thrown, because the expression will not execute the code after the null-safe accessor. In this case when getName() return null, the toUpperCase() method will never get called.

Below is the demo program code:

package org.kodejava.example.spring.el;

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

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

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

Here is the result of the code:

Name  = Alice
Grade = null

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={}}