Monday, October 4, 2021

What is Spring Expression Language (SpEL)? Difference between $ and # in @Value expressions Example

Hello Java programmers, if you are wondering what is Spring Expression Language and how to use them in your Spring application then you have come to the right place. Earlier, I have shared the best Spring Framework courses and books, and in this article, I am going to teach you about Spring Expression Langage with simple, easy-to-understand examples. The Spring Expression Language (SpEL for short) is a powerful language that supports querying and manipulating an object graph at runtime. The syntax is similar to Unified EL, but it has several more features, such as method calling and rudimentary string templating.


1. What is Spring Expression Language SpEL

The SpEL expression begins with the symbol of # and should be wrapped with braces as an example of #{}. There are several operators available on SpEL, some of them are mentioned in the following image:

What is Spring Expression Language (SpEL)? $ and # in @Value expressions Example


The SpEL expression begins with the symbol of # and should be wrapped with braces as an example of #{}. Property placeholders can not contain SpEL expressions but the expressions can have property references.

#{${propertyValues} + 2}

First, you have to add the following dependencies on the pom.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<dependencies>
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.0.8.RELEASE</version>
   </dependency>
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.8.RELEASE</version>
   </dependency>
   <dependency>
      <groupId>com.sun.mail</groupId>
      <artifactId>javax.mail</artifactId>
      <version>1.6.0</version>
   </dependency>
   <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
   </dependency>
</dependencies>


SpEL requires the first two dependencies, spring-core and spring-context. In a practical SpEL example, the other two dependencies, javax.mail and commons-io, will be employed.




So below we will discuss some of the arithmetic operators which we can use with SpEL expressions.

@Value("#{1+1}") // the addition value will be 2
private double addition;

@Value("#{2 - 1}") // the substraction value will be 1
private double substraction;

@Value("#{2 * 2}") // the multiplication value will be 4
private double multiply;

so this is special language use in Java as this allows constraints on the values before storing them in the classes.

SpEL supports all the logical operators. We will have some of the logical expressions which contain
the SpEL language is below.

@Value("#{1 > 0 && 2 < 4}") // this will give the andOperator true value
private boolean andOperator;

@Value("#{!true}") // this will give the notOperator true
private boolean notOperator;


So as from the above code segments, we can also implement this with other logical operators also.

Conditional operators also make a huge impact on the java application and the below example gives you a clear point of view of injecting the values with injecting values depending on certain conditions.

@Value("#{2 > 1 ? 'right' : 'wrong'}") // "right"
private String ternary;


The ternary operator is also commonly used to verify if a variable is null and then return the variable value or a default:  The matches operator is used to determine whether a string matches a regular expression.

@Value("#{'100' matches '\\d+' }") // true
private boolean validNumericStringResult;

@Value("#{'100fghdjf' matches '\\d+' }") // false
private boolean invalidNumericStringResult;





2. SpEL in Bean Configuration

Bean definitions can employ SpEL expressions. It's compatible with both XML and annotation-based configurations. A hash (#) symbol is used to start a SpEL expression, which is then enclosed in braces.

@Component("student")
public class User {
    @Value("112233")
    private Integer id;
    @Value("John")
    private String firstName;
    @Value("William")
    private String lastName;
    @Value("#{user.firstName.concat(' ').concat(user.lastName)}")
    private String fullName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }
}


In the above-annotated example, the beans which having the id, firstName, lastName, and fullName
are annotated with @Value which is used to restrict unwanted beans to be created with wrong values.

In summary, SpEL is a robust, well-supported expression language that can be used with any
Spring product. It can be used to configure Spring applications or to create parsers that can be used in any application to accomplish more generic tasks.

Other Java and Spring Articles you may like
  • 10 Spring MVC annotations Java developer should learn (annotations)
  • @SpringBootApplication vs @EnableAutoConfiguration? (answer)
  • 15 Spring Boot Interview Questions for Java Developers (questions)
  • Top 5 Courses to Learn and Master Spring Cloud (courses)
  • How Spring MVC works internally? (answer)
  • Spring Data JPA @Query Example (query example)
  • Spring Data JPA Repository (JpaReposistory example)
  • 5 Courses to learn Spring Cloud for Microservices (courses)
  • 5 Courses to Learn Spring Security for Java programmers (courses)
  • Top 5 Spring Boot Annotations Java Developers should know (read)
  • Difference between @RequestParam and @PathVariable in Spring (answer)
  • Top 7  Courses to learn Microservices in Java (courses)
  • Top 5 Frameworks Java Developer Should Know (frameworks)
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • Top 5 Spring Cloud annotations Java programmer should learn (cloud)
  • Difference between @Component, @Service, and @Controller in Spring (answer)
  • 20+ Spring MVC Interview Questions for Programmers (answer)
  • Difference between @Autowired and @Inject in Spring? (answer)
  • Difference between @Controller and @RestController in Spring (answer)
Thanks for reading this article so far. If you find this Spring JDBC tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are a beginner and want to learn the Spring framework, particularly Spring Boot from scratch, and looking for some free resources then you can also check out these free core Spring and Spring MVC courses for beginners. This list contains free Udemy and Pluralsight courses to learn Spring Framework from scratch. 

No comments :

Post a Comment