使用带有属性的 spring SPEL 调用方法

Osc*_*Ryz 6 java spring-el spring-boot

是否可以在赋值时使用属性值来调用方法?

例如,我知道我可以这样做:

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

我想知道是否可以做这样的事情:

@Value("#{myMethod(${name})}")
private String myModifiedVariable; // will have the result of invoking myMethod
Run Code Online (Sandbox Code Playgroud)

Dea*_*ool 6

经过我的研究和一些测试,我发现本文中显示了一种Spring EL方法调用的方式,但mybean应该是一个字符串bean

@Value("#{mybean.myMethod('${name}')}")
private String myModifiedVariable;
Run Code Online (Sandbox Code Playgroud)

如果你想调用现有类中的方法,那么使用同一个类的 spring bean 名称

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

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

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

  }
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,还有“#this”。 (2认同)