Spring SpEL - 属性

SpEL 表达式支持访问对象的属性。

  • 我们也可以在 SpEL 表达式中访问嵌套属性。

  • 在 SpEL 表达式中,属性的第一个字母不区分大小写。

以下示例显示了各种用例。


示例

让我们更新在 Spring SpEL - 创建项目 章节中创建的项目。 我们正在添加/更新以下文件 −

  • Employee.java − 员工类。

  • MainApp.java − 要运行和测试的主应用程序。

这是 Employee.java 文件的内容 −

实例


package com.tutorialspoint;

import java.util.Date;

public class Employee {
   private int id;
   private String name;	
   private Date dateOfBirth;

   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public Date getDateOfBirth() {
      return dateOfBirth;
   }
   public void setDateOfBirth(Date dateOfBirth) {
      this.dateOfBirth = dateOfBirth;
   }
   @Override
   public String toString() {
      return "[" + id + ", " + name + ", " + dateOfBirth + "]";
   }
}

这是 MainApp.java 文件的内容 −

实例


package com.tutorialspoint;

import java.text.ParseException;
import java.text.SimpleDateFormat;
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();
      Employee employee = new Employee();
      
      employee.setId(1);
      employee.setName("Mahesh");
      employee.setDateOfBirth(new SimpleDateFormat("YYYY-MM-DD").parse("1985-12-01"));

      EvaluationContext context = new StandardEvaluationContext(employee);
      
      int birthYear = (Integer) parser.parseExpression("dateOfBirth.Year + 1900").getValue(context);	
      System.out.println(birthYear);

      String name = (String) parser.parseExpression("name").getValue(context);	
      System.out.println(name);
   }
}

输出

1984
Mahesh