Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

Spring - Expression Language(SpEL)

Spring Expression Language (SpEL) is a powerful expression language that enables querying and manipulating objects at runtime. Introduced in Spring 3.0, SpEL can be used in XML and annotations to communicate (read and write) with properties, invoke methods, navigate objects, and more, all during the runtime of a Spring application.

Key Features:

  • Object graph navigation: Navigate properties, arrays, lists, maps, and even more complex types.
  • Method invocation: Call methods on objects.
  • Arithmetic, logical, and relational operators: Perform various operations and comparisons.
  • Regular expressions: Match and modify strings using regular expressions.
  • Collection projection and selection: Manipulate collections by selecting and projecting their data.
  • Safe navigation: Avoid NullPointerException using the safe navigation operator (?.).
  • Variables, properties, and lists: Reference and interact with various types of data structures.
  • Built-in functions: Utilize certain helper functions, like T() for type conversion.

Basic Syntax:

  • Properties: name, account.name
  • Lists: names[0]
  • Maps: userMap['admin']
  • Methods: getAccounts(), calculateAge()
  • Operators: 1 + 1, account.balance > 1000
  • Types: T(java.lang.String), T(java.util.Date)
  • Variables: #variableName

Usage Examples:

  • XML Configuration:
<bean id="sampleBean" class="com.example.SampleBean">
    <property name="value" value="#{anotherBean.propertyName}" />
</bean>
  • Annotation Configuration:
@Value("#{systemProperties['user.region']}")
private String defaultLocale;
  • Safe navigation:
@Value("#{user?.address?.zipcode}")
private String zipcode;
  • Type references:
@Value("#{T(java.lang.Math).PI}")
private double piValue;
  • List and Map Projections:
@Value("#{list.![someProperty]}")
private List<String> projectedProperties;

@Value("#{map.?[value > 10]}")
private Map<String, Integer> filteredMap;

Evaluation Context:

SpEL expressions can be evaluated using the ExpressionParser. The StandardEvaluationContext can be used to set variables, root objects, and other properties that the expression might need during evaluation.

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World!'.concat('!')");
String result = (String) exp.getValue();

SpEL offers extensive functionalities that cover a wide range of use cases. Whether you're configuring beans in XML, using annotations, or even working programmatically with Spring's API, SpEL provides a flexible way to define dynamic values and compute them at runtime.

  1. Introduction to SpEL in Spring framework:

    • SpEL is a powerful expression language introduced in Spring, providing a concise and expressive syntax for querying and manipulating objects during the configuration or runtime.
    // SpEL example in XML configuration
    <bean id="person" class="com.example.Person">
        <property name="fullName" value="#{ 'John ' + 'Doe' }" />
    </bean>
    
  2. Using SpEL for expression evaluation in Spring:

    • SpEL expressions can be used to evaluate dynamic values or perform operations within Spring beans.
    // SpEL example in annotation
    @Value("#{ T(java.lang.Math).random() * 100.0 }")
    private double randomValue;
    
  3. Dynamic property access with SpEL in Spring:

    • SpEL allows dynamic access to properties, making it useful for scenarios where property names are not known in advance.
    // SpEL dynamic property access
    @Value("#{ systemProperties['java.home'] }")
    private String javaHome;
    
  4. Conditional expressions with SpEL in Spring:

    • SpEL supports conditional expressions, enabling you to make decisions based on certain conditions.
    // SpEL conditional expression
    @Value("#{ user.age >= 18 ? 'Adult' : 'Minor' }")
    private String userStatus;
    
  5. How to use SpEL in Spring annotations:

    • SpEL can be integrated directly into Spring annotations to provide dynamic values or conditions.
    // SpEL in annotation
    @Value("#{ environment['app.mode'] }")
    private String appMode;
    
  6. Integration of SpEL with Spring XML configuration:

    • SpEL expressions can be used within Spring XML configuration files to dynamically set property values.
    // SpEL in XML configuration
    <property name="discount" value="#{ order.totalAmount > 1000 ? 0.1 : 0.05 }" />
    
  7. Accessing beans and properties with SpEL in Spring:

    • SpEL allows you to access other beans and their properties within expressions.
    // SpEL accessing beans and properties
    @Value("#{ userService.getUser().fullName }")
    private String userFullName;