In this post under Spring SpEL, I will show with example how to call an instance’s non-static method.
Below is the complete code for your reference.
Main class
1 package spel.package7;
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.stereotype.Component;
8
9 @Configuration
10 @ComponentScan(basePackages = "spel.package7")
11 public class Example7 {
12 @Value("#{'Hello Spring'.substring(6)}")
13 private String value;
14
15 public static void main(String[] args) {
16 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example7.class);
17 Example7 example7 = applicationContext.getBean(Example7.class);
18 System.out.println(example7.value);
19 }
20 }
In the above code, at line 12, I apply “@Value” annotation to “value” String variable.
To the “@Value” annotation, we pass a string as an argument.
The string consists of SpEL expression.
In the SpEL expression, we are creating a String object using String literal and calling “substring” method on the String.
The result of the String’s “substring” method is assigned to “value” variable.
In this way we can call an instance’s non-static method.
This method call syntax is same as we do in Java.