Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

Spring - Variable in SpEL

Spring Expression Language (SpEL) is a powerful expression language that supports querying and manipulation of objects during runtime. It's commonly used in Spring for configuration metadata, as well as by the Spring Security project.

One of the common use cases of SpEL is to reference beans, properties, and methods. Sometimes, you might want to use variables in SpEL expressions.

Setting up a SpEL with a Variable:

  1. Context Setting: When working directly with SpEL, you might set the context and the variables through StandardEvaluationContext.

    ExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext context = new StandardEvaluationContext();
    
    context.setVariable("variableName", "variableValue");
    String result = parser.parseExpression("This is a SpEL variable: #{#variableName}").getValue(context, String.class);
    
  2. Usage in @Value: You can use SpEL in the @Value annotation to inject values based on expressions.

    For example:

    @Value("#{systemProperties['user.home']}")
    private String userHome;
    

    Here, the SpEL expression fetches the system property user.home.

Using a variable in SpEL:

Let's say you want to use a variable to adjust the behavior of your bean. Here's an example:

  1. Properties File (application.properties):

    app.factor=10
    
  2. Spring Configuration:

    @Value("${app.factor}")
    private int factor;
    
  3. Usage with a method and SpEL:

    Let's say you have a method that multiplies a number with the factor from the properties file:

    public int multiplyWithFactor(int number) {
        ExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setVariable("inputNumber", number);
    
        // Fetching the factor from properties, multiplying with the input number
        return parser.parseExpression("#inputNumber * " + factor).getValue(context, Integer.class);
    }
    

    The method sets the inputNumber as a variable in the SpEL context and then evaluates the expression.

When working within Spring's environment, like in a @Service or @Component, and you've loaded properties using the @PropertySource annotation, you can reference those properties directly using SpEL in annotations like @Value.

Keep in mind that while SpEL is powerful, it can also make the code more complex and harder to read, especially if overused or used in complicated expressions. Always balance the benefits of dynamic runtime expression evaluation with code clarity and maintainability.

  1. Using variables in Spring SpEL expressions:

    • Description: Demonstrates how to use variables within SpEL expressions in a Spring application.
    • Code:
      @Value("#{myVariable + ' World'}")
      private String greeting;
      
  2. Conditional expressions with variables in SpEL:

    • Description: Demonstrates how to use variables in conditional expressions within SpEL.
    • Code:
      @Value("#{myCondition ? 'Value1' : 'Value2'}")
      private String result;
      
  3. Working with Map variables in Spring SpEL:

    • Description: Guides on using Map variables within SpEL expressions.
    • Code:
      @Value("#{myMap['key']}")
      private String mapValue;
      
  4. Accessing environment variables in SpEL:

    • Description: Shows how to access environment variables using SpEL.
    • Code:
      @Value("#{systemEnvironment['MY_ENV_VARIABLE']}")
      private String envVariable;
      
  5. Working with list and array variables in SpEL:

    • Description: Guides on using list and array variables within SpEL expressions.
    • Code:
      @Value("#{myList[0]}")
      private String listValue;