In this post under Spring SpEL, I will show with example how to access list in SpEL.
For our example I will create the below main class
Main class
1 package spel.package4;
2
3 import org.springframework.beans.factory.annotation.Value;
4 import org.springframework.context.ApplicationContext;
5 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
6 import org.springframework.context.annotation.Bean;
7 import org.springframework.context.annotation.ComponentScan;
8 import org.springframework.stereotype.Component;
9
10 import java.util.ArrayList;
11 import java.util.List;
12
13 @Configuration
14 @ComponentScan(basePackages = "spel.package4")
15 public class Example4 {
16 @Value("#{colorList[1]}")
17 private String rgbComposition;
18
19 @Bean
20 public List<String> colorList() {
21 List<String> rgbComositionList = new ArrayList<>(0);
22 rgbComositionList.add("10, 90, 200");
23 rgbComositionList.add("50, 100, 90");
24 return rgbComositionList;
25 }
26
27 public String getRgbComposition() {
28 return rgbComposition;
29 }
30
31 public void setRgbComposition(String rgbComposition) {
32 this.rgbComposition = rgbComposition;
33 }
34
35 public static void main(String[] args) {
36 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example4.class);
37 Example4 example4 = applicationContext.getBean(Example4.class);
38 System.out.println(example4.getRgbComposition());
39 }
40 }
In the above code at line 16, I create an SpEL which accesses the list “colorList”, gets the value at index 1 and set the “rgbComposition” instance variable of “Example4” class to “50, 100, 90”.
In this way we can access a list in SpEL.