Ternary operator in SpEL

In this post under Spring SpEL, I will show with example how to use ternary operator in SpEL.

Below is the main class for your reference.

Main class

1  package spel.package18;
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.Configuration;
8  
9  import java.util.Arrays;
10 import java.util.List;
11 
12 @Configuration
13 public class Example18 {
14     @Value("#{(integerList.size() % 2) == 0 ? true : false}")
15     public boolean evenPopulated;
16 
17     @Bean
18     public List<Integer> integerList() {
19         List<Integer> list = Arrays.asList(1, 2, 3, 4);
20         return list;
21     }
22 
23     public static void main(String[] args) {
24         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example18.class);
25         Example18 example5 = applicationContext.getBean(Example18.class);
26         System.out.println(example5.evenPopulated);
27     }
28 }

In the above code, at line 14 we are using ternary operator in the SpEL expression.

In this way we can use ternary operator in SpEL

Leave a comment