Projecting collections in SpEL

In this post under Spring SpEL, I will show with example how to project certain fields of a collection of objects instead of whole object itself.

For our example, we use the below class structure

Employee

package spel.package13;

public class Employee {
    private int id;
    private String name;
    private int salary;

    public Employee(int id, String name, int salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }
    //Removed getter and setter for brevity
}

Below is the main method showing how to use project certain fields of collection of an object instead of entire object itself.

Main class

package spel.package13;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import spel.package11.Employee;

import java.util.ArrayList;
import java.util.List;

@Configuration
@ComponentScan(basePackages = "spel.package13")
public class Example13 {
    @Value("#{employees.![salary]}")
    private List<Long> salaryList;

    @Bean("employees")
    public List<spel.package11.Employee> getEmployees() {
        List<spel.package11.Employee> list = new ArrayList<>(0);
        for(int i = 1; i <= 10; i++) {
            spel.package11.Employee employee = new Employee(i, "name" + i, (i * 100));
            list.add(employee);
        }

        return list;
    }

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example13.class);
        Example13 example = applicationContext.getBean(Example13.class);
        for(Long salary : example.salaryList) {
            System.out.println(salary);
        }
    }
}

In the above code, the “getEmployees” method create a list of 10 employees.

Now the requirement is for every employee present in the collection we only want their salary information.

This requirement is implemented using SpEL expression at line 17. The syntax is shown below

  collectionName.![field to extract]

In our case the “collectionName” is “employees” bean followed by “.!” operator and then followed by field “salary” within the square bracket.

So Spring will loop through collection of employees, extract their salary field and put it in a new collection. This new collection is assigned to “salaryList” variable.

We print the contents of “salaryList” in the for loop at line 34.

In this way we can project certain fields of collections of an object instead of getting the entire object itself

Leave a comment