In this post under Spring SpEL, I will show how to access array elements in SpEL expressions.
For our example I will use the two beans. Below is the class structure of them
Bean1 class
package spel.package2;
import org.springframework.stereotype.Component;
@Component
public class Bean1 {
private int[] values = new int[] {1, 2, 3, 4};
public int[] getValues() {
return values;
}
public void setValues(int[] values) {
this.values = values;
}
}
In the above class, I have created an instance variable of type array storing integer values. The name of the variable is “values” and it is initialized with some default values.
Bean2 class
1 package spel.package2;
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.values[2] * 2}")
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 “@Value” annotation with instance variable “value” of class “Bean2”.
The “@Value” annotation has an SpEL expression.
The expression retrieves the value from array stored in “bean1” object and multiply it with 2 and the result is stored in “value” variable of “Bean2” class.
We are accessing value at 2nd position of “values” array present in the “Bean1” class.
In this way we can access an array in SpEL.