Refering User Defined Classes in SpEL

In all my previous post, I used classes provided by Java.

In this post, I will explain how to refer user defined classes.

For our example I will create a user defined class “Student” with below class structure.

Student

package spel.package10;

public class Student {
    private int id;
    private String name;

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    //Removed getter and setter for brevity
}

Next is the main class

Main class

1  package spel.package10;
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 @Configuration
11 @ComponentScan(basePackages = "spel.package10")
12 public class Example10 {
13     @Value("#{student.name}")
14     private String value;
15 
16     @Bean("student")
17     public Student getStudent() {
18         return new Student(10, "Sumanth");
19     }
20 
21     public static void main(String[] args) {
22         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example10.class);
23         Example10 example10 = applicationContext.getBean(Example10.class);
24         System.out.println(example10.value);
25     }
26 }

In the above main class. At line 17, I create “getStudent” method which will create and return a bean of name “student”.

Then at line 14, I created a String variable named “value” and I associate it with an SpEL expression refer to line 13.

In the SpEL expression, I refer to “Student” class bean by its bean name, which is “student” and then access its property “name”.

The value of Student’s class “name” property is set to “value” variable of “Example10” class.

In this way we can refer to user defined beans in SpEL.

Leave a comment