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
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";
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With