Spring SpEL - Constructor



SpEL expression supports creating objects within expressions using new operator. We need to pass the fully qualified name of the class.

Syntax

Employee robert = parser.parseExpression("new com.tutorialspoint.Employee('Robert','USA')").getValue(Employee.class);

Following example shows the various use cases.

Example

Let's update the project created in Spring SpEL - Create Project chapter. We're adding/updating following files −

  • Employee.java − Employee class.

  • Dept.java − Department class.

  • MainApp.java − Main application to run and test.

Here is the content of Employee.java file −

package com.tutorialspoint;

public class Employee {
   private String name;
   private String country;

   public Employee(String name, String country) {
      this.name = name;
      this.country = country;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getCountry() {
      return country;
   }
   public void setCountry(String country) {
      this.country = country;
   }
   public String toString() {
      return "[" +name+ ", "+country + "]";
   }
}

Here is the content of Dept.java file −

package com.tutorialspoint;

import java.util.List;

public class Dept {
   private List<Employee> employees;

   public List<Employee> getEmployees() {
      return employees;
   }
   public void setEmployees(List<Employee> employees) {
      this.employees = employees;
   }
   public String toString() {
      return "[" + employees.toString() + "]";
   }
}

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException {
      ExpressionParser parser = new SpelExpressionParser();

      List<Employee> employees = new ArrayList<Employee>();	   
      Employee robert = parser.parseExpression("new com.tutorialspoint.Employee('Robert','USA')")
         .getValue(Employee.class);
      employees.add(robert);

      Dept dept = new Dept();
      dept.setEmployees(employees);
      System.out.println(dept);

      EvaluationContext deptContext = new StandardEvaluationContext(dept);
      parser.parseExpression("employees.add(new com.tutorialspoint.Employee('Julie','USA'))")
         .getValue(deptContext);
      System.out.println(dept);
   }
}

Output

[[[Robert, USA]]]
[[[Robert, USA], [Julie, USA]]]
Advertisements