Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke method using spring SPEL with property

Is it possible to use a property value to invoke a method while assigning a value?

For instance, I know I can do this:

@Value("${name}")
private String name; // will have the value of the `name` property

I wonder if it's possible to do something like this:

@Value("#{myMethod(${name})}")
private String myModifiedVariable; // will have the result of invoking myMethod
like image 924
OscarRyz Avatar asked Jul 26 '26 07:07

OscarRyz


2 Answers

After my research and a bit of testing, I found there is a way shown in this article Spring EL method invocation, But mybean should be a string bean

@Value("#{mybean.myMethod('${name}')}")
private String myModifiedVariable;

And if you want to call a method in the existing class then use the spring bean name of the same class

 @Configuration  // or any sterotype annoations
 public class TestConfig {

       @Value("#{testConfig.myMethod('${name}')}")
       private String myModifiedVariable;

       public String getValue(String val){
             return val+"testValue";
       }

  }
like image 127
Deadpool Avatar answered Jul 28 '26 21:07

Deadpool


When using interface projection (in Spring Data Repository) it is possible to call a static method like this:

public interface MyProjection {
  // Here we are creating a 2 element list with 'Spring Data' and value taken from "MY_COLUMN_NAME" column
  @Value("#{T(java.util.Arrays).asList('Spring Data', target.MY_COLUMN_NAME)}")
  List<String> getSampleList(); 
}

You can also obtain a value of an enum (constant) with above notation. Sample for Spring Security check:

@PreAuthorize("hasRole(T(com.acme.UserRoles).ADMINISTRATOR.name())")

Similar notation should work in other places. Simply remember to use full path to class

like image 36
kgtgit Avatar answered Jul 28 '26 22:07

kgtgit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!