Invoking Constructors in SpEL

In this post under Spring SpEL, I will show with example how to invoke constructors.

Below is the complete code for your reference

Main class

1  package spel.package9;
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.ComponentScan;
7  import org.springframework.context.annotation.Configuration;
8  import java.util.List;
9  
10 @Configuration
11 @ComponentScan(basePackages = "spel.package9")
12 public class Example9 {
13     @Value("#{new Integer(10)}")
14     private Integer value;
15 
16     @Value("#{new java.util.ArrayList(10)}")
17     private List<Integer> list;
18 
19     public static void main(String[] args) {
20         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example9.class);
21         Example9 example9 = applicationContext.getBean(Example9.class);
22         System.out.println(example9.value);
23         System.out.println(example9.list.isEmpty());
24     }
25 }

In the above code at line 14 and 17, I created two instance variable.

First variable “value” is of type integer and I am using SpEL (refer to line 13) to initialize it.

Second variable “list” is of type List and I am using SpEL (refer to line 16) to initialize it.

In this way, we can call constructors in SpEL.

Leave a comment