In this post under Spring SpEL, I will give a simple example that shows how to access bean properties and use literal values in SpEL expressions.
SpEL (Spring Expression Language) is an expression language that supports querying and manipulating objects at runtime.
This expression language is written within “${ and “}” when used inside annotation or xml file.
For our example I will use two beans with below class structure
Bean1 class
package spel.package1;
import org.springframework.stereotype.Component;
@Component
public class Bean1 {
private int value = 10;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
As shown in the above code, “Bean1” class has only one property “value” set to 10 by default.
Bean2 class
1 package spel.package1;
2
3 import org.springframework.beans.factory.annotation.Value;
4 import org.springframework.stereotype.Component;
5
6 @Component
7 public class Bean2 {
8 @Value("#{bean1.value + 10}")
9 private int value;
10
11 public int getValue() {
12 return value;
13 }
14
15 public void setValue(int value) {
16 this.value = value;
17 }
18 }
In the above code, at line 8, I have used the “@Value” annotation to the set the value of instance variable “value”.
In my previous post, I told that we use “@Value” annotation to retrieve values from properties file and set it to variable to which this annotation is attached.
Here instead of retrieving values from properties file, we are telling Spring framework to execute a SpEL expression.
In the expression we are retrieving the value of variable “value” stored in “Bean1” instance and add literal 10 to the retrieved value. The result of this expression is stored in “value” variable of
“Bean2” class.
In this way we can write SpEL when used with annotation.
Below is the main class for your reference.
Main class
package spel.package1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "spel.package1")
public class Example1 {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example1.class);
Bean2 bean2 = applicationContext.getBean(Bean2.class);
System.out.println(bean2.getValue());
}
}