Cover Image for Spring Operators in SpEL
172 views

Spring Operators in SpEL

Spring Expression Language (SpEL) provides a variety of operators that you can use to perform operations and comparisons within expressions. These operators enable you to work with data, manipulate strings, and evaluate conditions in SpEL expressions. Here are some of the commonly used operators in SpEL:

1. Arithmetic Operators:

  • +: Addition
  #{2 + 3}   // Result: 5
  • -: Subtraction
  #{10 - 5}  // Result: 5
  • *: Multiplication
  #{2 * 3}   // Result: 6
  • /: Division
  #{10 / 2}  // Result: 5
  • %: Modulus (Remainder)
  #{10 % 3}  // Result: 1

2. Relational Operators:

  • ==: Equal to
  #{age == 18}  // Result: true or false
  • !=: Not equal to
  #{score != 100}  // Result: true or false
  • <: Less than
  #{marks < 50}  // Result: true or false
  • >: Greater than
  #{price > 20.0}  // Result: true or false
  • <=: Less than or equal to
  #{count <= 5}  // Result: true or false
  • >=: Greater than or equal to
  #{total >= 100}  // Result: true or false

3. Logical Operators:

  • and or &&: Logical AND
  #{isAdult and hasLicense}  // Result: true or false
  • or or ||: Logical OR
  #{isAdmin or hasPermission}  // Result: true or false
  • not or !: Logical NOT
  #{not isDisabled}  // Result: true or false

4. Conditional Operator:

  • ? : (Ternary operator): Conditional expression
  #{isAdult ? 'Adult' : 'Minor'}  // Result: 'Adult' or 'Minor'

5. Elvis Operator:

  • ?:: Elvis operator (null-safe operator)
  #{name ?: 'Unknown'}  // Result: 'Unknown' if name is null

6. Regular Expression Operator:

  • matches: Checks if a string matches a regular expression
  #{email.matches('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}')}  // Result: true or false

7. Conditional (Safe Navigation) Operator:

  • ?.: Safe navigation operator (used to prevent null-pointer exceptions)
  #{person?.address?.city}  // Result: city or null if person or address is null

These operators allow you to build complex expressions in SpEL for various use cases, including bean property access, data manipulation, and conditional logic. SpEL is a versatile language that can be used in Spring configuration files, annotations, and other parts of your Spring application to dynamically configure and evaluate expressions.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS