Wednesday, November 20, 2024
Google search engine
HomeLanguagesJavaSpring – Expression Language(SpEL)

Spring – Expression Language(SpEL)

SpEL is a scripting language that allows you to query and manipulate an object graph in real-time. JSP EL, OGNL, MVEL, and JBoss EL are just a few of the expression languages accessible. Method invocation and string templating are two of the extra functionalities provided by SpEL.

API for SpEL: Many interfaces and classes are available in the SpEL API. The following are the details:

  1. Expression interface
  2. SpelExpression class
  3. ExpressionParser interface
  4. SpelExpressionParser class
  5. EvaluationContext interface
  6. StandardEvaluationContext class

Dependencies: Add the following dependencies:

  • spring-core
  • spring-context
  • spring-beans

Implementation: The project structure looks like as depicted in the below media as follows: 

A. File: pom.xml

XML




    <modelVersion>4.0.0</modelVersion>
    <groupId>com.neveropen.spring</groupId>
    <artifactId>springListExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>
 
    <properties>
        <spring.version>3.2.3.RELEASE</spring.version>
    </properties>
</project>


Spring Context XML Expression Support

To make the configuration easier, we may employ spring expressions within the XML context. We will start with our example and then move on to the POJO classes.

Here is an example, we are having a training program built around a lesson that covers a variety of technical subjects. The course will focus on a specific subject.

B. File: Topic.java

Java




// Java Program to Illustrate Topic Class
 
package com.neveropen.spring;
 
// Class
public class Topic {
 
    // Class data members
    private String name;
 
    // Constructor: Default
    public Topic() {}
 
    // Constructor: Parameterized
    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. File: Tutorial.java

Java




// Java Program to Illustrate Tutorial Class
 
package com.neveropen.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. File: Training.java

Java




// Java Program to Illustrate Training Class
 
package com.neveropen.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;
    }
}


We shall define a couple of technical subjects, java core, and ScalaBasics, as well as a lesson and training, in the context of XML. When defining the beans, SpEL expressions can be combined with XML. #expression string> is the syntax.

#tutorial.topicsList[1] is used to set the topic of our training bean. It sets the subject property to the second topic from the instructional bean’s list of topics.

E. File: applicationContext.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
 
 
     <context:component-scan base-package="com.neveropen.spring" />
 
    <bean id="tutorial" class="com.neveropen.spring.Tutorial">
        <property name="topicsList">
           <ref local="javaCore" />
           <ref local="scalaBasics" />
        </property>
    </bean>
         
    <bean id="javaCore" class="com.neveropen.spring.Topic">
        <property name="name" value="JavaCore" />
    </bean>
     
    <bean id="scalaBasics" class="com.neveropen.spring.Topic">
        <property name="name" value="ScalaBasics" />
    </bean>   
     
    <bean id="training" class="com.neveropen.spring.Training">
        <property name="topic" value="#{tutorial.topicsList[1]}"/>
    </bean>
     
</beans>


F. FIle: SpringExpressionXmlContextExample.java

Java




// Java Program to Illustrate Application Class
 
package com.neveropen.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();
        }
    }
}


Output:

ScalaBasics

Annotation in Spring Expressions

SpEL expressions may also be used to define beans using annotation-based configuration metadata. To define a default value, use the @Value annotation on fields, methods, and method/constructor arguments.

We’ve added a new member defaultTopic to our Training bean to show the example. To set the defaultTopic, we utilized a spring expression.

File: Training.java

Java




package com.neveropen.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;
    }
}


The annotations are scanned and assessed by adding the context: the component-scan element to the context XML.

File: applicationContext.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
 
 
     <context:component-scan base-package="com.neveropen.spring" />
 
    <bean id="tutorial" class="com.neveropen.spring.Tutorial">
        <property name="topicsList">
          <ref local="javaCore" />
          <ref local="scalaBasics" />
        </property>
    </bean>
         
    <bean id="javaCore" class="com.neveropen.spring.Topic">
        <property name="name" value="JavaCore" />
    </bean>
     
    <bean id="scalaBasics" class="com.neveropen.spring.Topic">
        <property name="name" value="ScalaBasics" />
    </bean>   
     
    <bean id="training" class="com.neveropen.spring.Training">
        <property name="topic" value="#{tutorial.topicsList[1]}"/>
    </bean>
     
</beans>


Let’s see whether defaultTopic is enabled.

File: SpringExpressionXmlContextExample.java

Java




package com.neveropen.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();
        }
    }
}


Output:

ScalaBasics
JavaCore

Spring Expression Language Parser Example

Using the expression parser, the SpEL may also be utilized as a standalone component.

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

File: SpringExpressionParserExample.java

Java




package com.neveropen.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.neveropen.spring.Topic('Java')").getValue(Topic.class).getClass());      
    }
}


Output:

Let’s have a look at a couple more instance: Using Spring ExpressionParser to call a method where in this example, we call String‘s substring(), length().

File: SpringExpressionParserExample.java

Java




package com.neveropen.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());       
    }
}


Output:

Access JavaBean Properties using Spring ExpressionParser

Let’s access a couple of JavaBean properties classes and bytes of the String objects.

File: SpringExpressionParserExample.java

Java




// Java Program to Illustrate Spring Expression Parser
 
package com.neveropen.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());
    }
}


Output:
 

Calling Constructor using Spring ExpressionParser

We can create an object by calling the constructor of the class in the spring expression. For example:

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

File: SpringExpressionParserExample.java

Java




// Java Program to Illustrate Spring Expression Parser
 
package com.neveropen.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.neveropen.spring.Topic('Java')")
                .getValue(Topic.class)
                .getClass());
    }
}


Output:

RELATED ARTICLES

Most Popular

Recent Comments