In this post under Spring SpEL, I will show with example how to access map in SpEL.
For our example I will create the below main class
Main class
1 package spel.package3;
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.context.annotation.Configuration;
9
10 import java.util.HashMap;
11 import java.util.Map;
12
13 @Configuration
14 @ComponentScan(basePackages = "spel.package3")
15 public class Example3 {
16 @Value("#{numberToMonthMap[1]}")
17 private String month;
18
19 public String getMonth() {
20 return month;
21 }
22
23 @Bean
24 public Map<Integer, String> numberToMonthMap() {
25 Map<Integer, String> numberToMonthMap = new HashMap<>(0);
26 numberToMonthMap.put(1, "January");
27 numberToMonthMap.put(2, "Febraury");
28 numberToMonthMap.put(3, "March");
29 return numberToMonthMap;
30 }
31
32 public static void main(String[] args) {
33 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example3.class);
34 Example3 example3 = applicationContext.getBean(Example3.class);
35 System.out.println(example3.getMonth());
36 }
37 }
In the above code at line 16, I create an SpEL which accesses the map, get the value of key “1” and set the “month” instance variable of “Example3” class to “January”.
In this way we can access a map in SpEL.