'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


Solution 1:[1]

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";
       }

  }

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 kgtgit