📜  Spring - 表达语言(SpEL)

📅  最后修改于: 2022-05-13 01:55:50.975000             🧑  作者: Mango

Spring - 表达语言(SpEL)

SpEL 是一种脚本语言,可让您实时查询和操作对象图。 JSP EL、OGNL、MVEL 和 JBoss EL 只是一些可访问的表达式语言。方法调用和字符串模板是 SpEL 提供的两个额外功能。

SpEL API: SpEL API 中提供了许多接口和类。以下是详细信息:

  1. 表达式接口
  2. SpelExpression 类
  3. 表达式解析器接口
  4. SpelExpressionParser 类
  5. 评估上下文接口
  6. StandardEvaluationContext 类

实施:项目结构如下图所示:  

A. 文件:pom.xml

XML

    4.0.0
    com.geeksforgeeks.spring
    springListExample
    0.0.1-SNAPSHOT
 
    
        
            org.springframework
            spring-core
            ${spring.version}
        
        
            org.springframework
            spring-context
            ${spring.version}
        
        
            org.springframework
            spring-beans
            ${spring.version}
        
    
 
    
        3.2.3.RELEASE
    


Java
// Java Program to Illustrate Topic Class
 
package com.geeksforgeeks.spring;
 
// Class
public class Topic {
 
    // Class data members
    private String name;
 
    // Constructor: Default
    public Topic() {}
 
    // Constructor: Parametrized
    public Topic(String name) { this.name = name; }
 
    // Getters and setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String toString() { return name; }
}


Java
// Java Program to Illustrate Tutorial Class
 
package com.geeksforgeeks.spring;
 
// Importing required classes
import java.util.ArrayList;
import java.util.List;
 
// Class
public class Tutorial {
 
    // Class data members
    private String name;
 
    private List topicsList = new ArrayList<>();
 
    // Getter
    public String getName() { return name; }
 
    // Setter
    public void setName(String name) { this.name = name; }
 
    // Method
    public List getTopicsList() { return topicsList; }
 
    // Setter
    public void setTopicsList(List topicsList)
    {
        this.topicsList = topicsList;
    }
 
    // Method
    // Overloading toString() method
    public String toString() { return name + topicsList; }
}


Java
// Java Program to Illustrate Training Class
 
package com.geeksforgeeks.spring;
 
// Class
public class Training {
 
    // Class data member
    private Topic topic;
 
    // Getter
    public Topic getTopic() { return topic; }
 
    // Setter
    public void setTopic(Topic topic)
    {
        this.topic = topic;
    }
}


XML

 

 
     
 
    
        
           
           
        
    
         
    
        
    
     
    
        
       
     
    
        
    
     


Java
// Java Program to Illustrate Application Class
 
package com.geeksforgeeks.spring;
 
// Importing required classes
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
// Main Class
public class SpringExpressionXmlContextExample {
 
    // Main driver method
    public static void main(String[] args)
    {
        ClassPathXmlApplicationContext context
            = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
 
        // Try block to check for exceptions
        try {
            Training training
                = (Training)context.getBean("training");
            System.out.println(training.getTopic());
 
            System.out.println(training.getDefaultTopic());
        }
 
        // finally block that will execute for sure
        finally {
 
            // Closing the connections
            // using close() method
            context.close();
        }
    }
}


Java
package com.geeksforgeeks.spring;
  
import org.springframework.beans.factory.annotation.Value;
  
public class Training
{
    private Topic topic;
      
    @Value("#{tutorial.topicsList[0]}")
    private Topic defaultTopic;
  
  //getters and setters
    public Topic getTopic()
    {
        return topic;
    }
  
    public void setTopic(Topic topic)
    {
        this.topic = topic;
    }
      
    public Topic getDefaultTopic()
    {
        return defaultTopic;
    }
}


XML

 

 
     
 
    
        
          
          
        
    
         
    
        
    
     
    
        
       
     
    
        
    
     


Java
package com.geeksforgeeks.spring;
 
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class SpringExpressionXmlContextExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            Training training = (Training) context.getBean("training");
            System.out.println(training.getTopic()); 
             
            System.out.println(training.getDefaultTopic());
        } finally {
            context.close();
        }
    }
}


Java
package com.geeksforgeeks.spring;
 
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
 
public class SpringExpressionParserExample {
    public static void main(String[] args) {
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("'Just a string value'");
        String message = (String) exp.getValue();
        System.out.println(message);
         
        System.out.println(parser.parseExpression("'Just a string value'.substring(5)").getValue());
         
        System.out.println(parser.parseExpression("'Just a string value'.length()").getValue());
         
        System.out.println(parser.parseExpression("'Just a string value'.substring('Just '.length())").getValue());
         
        System.out.println(parser.parseExpression("'Just a string value'.class").getValue());
         
        System.out.println(parser.parseExpression("'Just a string value'.bytes").getValue());
         
        System.out.println(parser.parseExpression("new com.geeksforgeeks.spring.Topic('Java')").getValue(Topic.class).getClass());      
    }
}


Java
package com.geeksforgeeks.spring;
 
import java.util.Arrays;
 
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
  
public class SpringExpressionParserExample {
    public static void main(String[] args) {
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("'Just a string value'");
        String message = (String) exp.getValue();
        System.out.println(message);
          
        System.out.println(parser.parseExpression("'Just a string value'.substring(5)").getValue());
          
        System.out.println(parser.parseExpression("'Just a string value'.length()").getValue());
          
        System.out.println(parser.parseExpression("'Just a string value'.substring('Just '.length())").getValue());       
    }
}


Java
// Java Program to Illustrate Spring Expression Parser
 
package com.geeksforgeeks.spring;
 
// Importing required classes
import java.util.Arrays;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
 
// Class
public class SpringExpressionParserExample {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        SpelExpressionParser parser
            = new SpelExpressionParser();
        Expression exp = parser.parseExpression(
            "'Just a string value'");
        String message = (String)exp.getValue();
 
        // Print commands
        System.out.println(message);
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.substring(5)")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.length()")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.substring('Just '.length())")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.class")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.bytes")
                .getValue());
    }
}


Java
// Java Program to Illustrate Spring Expression Parser
 
package com.geeksforgeeks.spring;
 
// Importing required classes
import java.util.Arrays;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
 
// Class
public class SpringExpressionParserExample {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        SpelExpressionParser parser
            = new SpelExpressionParser();
        Expression exp = parser.parseExpression(
            "'Just a string value'");
        String message = (String)exp.getValue();
        System.out.println(message);
 
        // Print commands
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.substring(5)")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.length()")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.substring('Just '.length())")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.class")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.bytes")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "new com.geeksforgeeks.spring.Topic('Java')")
                .getValue(Topic.class)
                .getClass());
    }
}


Spring 上下文 XML 表达式支持

为了使配置更容易,我们可以在 XML 上下文中使用 spring 表达式。我们将从示例开始,然后转到 POJO 类。

这是一个示例,我们正在围绕涵盖各种技术主题的课程构建培训计划。该课程将侧重于特定主题。

B. 文件:主题。Java

Java

// Java Program to Illustrate Topic Class
 
package com.geeksforgeeks.spring;
 
// Class
public class Topic {
 
    // Class data members
    private String name;
 
    // Constructor: Default
    public Topic() {}
 
    // Constructor: Parametrized
    public Topic(String name) { this.name = name; }
 
    // Getters and setters
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String toString() { return name; }
}

C. 文件:教程。Java

Java

// Java Program to Illustrate Tutorial Class
 
package com.geeksforgeeks.spring;
 
// Importing required classes
import java.util.ArrayList;
import java.util.List;
 
// Class
public class Tutorial {
 
    // Class data members
    private String name;
 
    private List topicsList = new ArrayList<>();
 
    // Getter
    public String getName() { return name; }
 
    // Setter
    public void setName(String name) { this.name = name; }
 
    // Method
    public List getTopicsList() { return topicsList; }
 
    // Setter
    public void setTopicsList(List topicsList)
    {
        this.topicsList = topicsList;
    }
 
    // Method
    // Overloading toString() method
    public String toString() { return name + topicsList; }
}

D. 文件:培训。Java

Java

// Java Program to Illustrate Training Class
 
package com.geeksforgeeks.spring;
 
// Class
public class Training {
 
    // Class data member
    private Topic topic;
 
    // Getter
    public Topic getTopic() { return topic; }
 
    // Setter
    public void setTopic(Topic topic)
    {
        this.topic = topic;
    }
}

我们将在 XML 的上下文中定义几个技术主题、 Java核心和 ScalaBasics,以及课程和培训。定义 bean 时,SpEL 表达式可以与 XML 结合使用。 #expression 字符串> 是语法。

#tutorial.topicsList[1] 用于设置我们训练 bean 的主题。它将主题属性设置为教学 bean 主题列表中的第二个主题。

E. 文件:applicationContext.xml

XML


 

 
     
 
    
        
           
           
        
    
         
    
        
    
     
    
        
       
     
    
        
    
     

F. 文件:SpringExpressionXmlContextExample。Java

Java

// Java Program to Illustrate Application Class
 
package com.geeksforgeeks.spring;
 
// Importing required classes
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
// Main Class
public class SpringExpressionXmlContextExample {
 
    // Main driver method
    public static void main(String[] args)
    {
        ClassPathXmlApplicationContext context
            = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
 
        // Try block to check for exceptions
        try {
            Training training
                = (Training)context.getBean("training");
            System.out.println(training.getTopic());
 
            System.out.println(training.getDefaultTopic());
        }
 
        // finally block that will execute for sure
        finally {
 
            // Closing the connections
            // using close() method
            context.close();
        }
    }
}

输出:

ScalaBasics

Spring 表达式中的注解

SpEL 表达式也可用于使用基于注释的配置元数据来定义 bean。要定义默认值,请在字段、方法和方法/构造函数参数上使用 @Value 注释。

我们在 Training bean 中添加了一个新成员defaultTopic 以显示示例。为了设置 defaultTopic,我们使用了一个 spring 表达式。

资料:培训。Java

Java

package com.geeksforgeeks.spring;
  
import org.springframework.beans.factory.annotation.Value;
  
public class Training
{
    private Topic topic;
      
    @Value("#{tutorial.topicsList[0]}")
    private Topic defaultTopic;
  
  //getters and setters
    public Topic getTopic()
    {
        return topic;
    }
  
    public void setTopic(Topic topic)
    {
        this.topic = topic;
    }
      
    public Topic getDefaultTopic()
    {
        return defaultTopic;
    }
}

通过将上下文添加到上下文 XML 中的组件扫描元素来扫描和评估注释。

文件:applicationContext.xml

XML


 

 
     
 
    
        
          
          
        
    
         
    
        
    
     
    
        
       
     
    
        
    
     

文件:SpringExpressionXmlContextExample。Java

Java

package com.geeksforgeeks.spring;
 
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class SpringExpressionXmlContextExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            Training training = (Training) context.getBean("training");
            System.out.println(training.getTopic()); 
             
            System.out.println(training.getDefaultTopic());
        } finally {
            context.close();
        }
    }
}

输出:

ScalaBasics
JavaCore

Spring 表达式语言解析器示例

使用表达式解析器,SpEL 也可以用作独立组件。

org.springframework.expression.spel.standard.SpelExpressionParser.

文件:SpringExpressionParserExample。Java

Java

package com.geeksforgeeks.spring;
 
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
 
public class SpringExpressionParserExample {
    public static void main(String[] args) {
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("'Just a string value'");
        String message = (String) exp.getValue();
        System.out.println(message);
         
        System.out.println(parser.parseExpression("'Just a string value'.substring(5)").getValue());
         
        System.out.println(parser.parseExpression("'Just a string value'.length()").getValue());
         
        System.out.println(parser.parseExpression("'Just a string value'.substring('Just '.length())").getValue());
         
        System.out.println(parser.parseExpression("'Just a string value'.class").getValue());
         
        System.out.println(parser.parseExpression("'Just a string value'.bytes").getValue());
         
        System.out.println(parser.parseExpression("new com.geeksforgeeks.spring.Topic('Java')").getValue(Topic.class).getClass());      
    }
}

输出:

文件:SpringExpressionParserExample。Java

Java

package com.geeksforgeeks.spring;
 
import java.util.Arrays;
 
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
  
public class SpringExpressionParserExample {
    public static void main(String[] args) {
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("'Just a string value'");
        String message = (String) exp.getValue();
        System.out.println(message);
          
        System.out.println(parser.parseExpression("'Just a string value'.substring(5)").getValue());
          
        System.out.println(parser.parseExpression("'Just a string value'.length()").getValue());
          
        System.out.println(parser.parseExpression("'Just a string value'.substring('Just '.length())").getValue());       
    }
}

输出:

使用 Spring ExpressionParser 访问 JavaBean 属性

让我们访问几个 JavaBean 属性类和 String 对象的字节。

文件:SpringExpressionParserExample。Java

Java

// Java Program to Illustrate Spring Expression Parser
 
package com.geeksforgeeks.spring;
 
// Importing required classes
import java.util.Arrays;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
 
// Class
public class SpringExpressionParserExample {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        SpelExpressionParser parser
            = new SpelExpressionParser();
        Expression exp = parser.parseExpression(
            "'Just a string value'");
        String message = (String)exp.getValue();
 
        // Print commands
        System.out.println(message);
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.substring(5)")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.length()")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.substring('Just '.length())")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.class")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.bytes")
                .getValue());
    }
}

输出:

使用 Spring ExpressionParser 调用构造函数

我们可以通过调用spring表达式中类的构造函数来创建对象。例如:

'new com.geeksforgeeks.spring.Topic('Java')'

文件:SpringExpressionParserExample。Java

Java

// Java Program to Illustrate Spring Expression Parser
 
package com.geeksforgeeks.spring;
 
// Importing required classes
import java.util.Arrays;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
 
// Class
public class SpringExpressionParserExample {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        SpelExpressionParser parser
            = new SpelExpressionParser();
        Expression exp = parser.parseExpression(
            "'Just a string value'");
        String message = (String)exp.getValue();
        System.out.println(message);
 
        // Print commands
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.substring(5)")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.length()")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.substring('Just '.length())")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.class")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "'Just a string value'.bytes")
                .getValue());
 
        System.out.println(
            parser
                .parseExpression(
                    "new com.geeksforgeeks.spring.Topic('Java')")
                .getValue(Topic.class)
                .getClass());
    }
}

输出: