簡體   English   中英

使用具有屬性的 spring SPEL 調用方法

[英]Invoke method using spring SPEL with property

是否可以在賦值時使用屬性值來調用方法?

例如,我知道我可以這樣做:

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

我想知道是否有可能做這樣的事情:

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

經過我的研究和一些測試,我發現這篇文章中顯示了一種方法Spring EL 方法調用,但mybean應該是一個字符串bean

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

如果你想在現有的 class 中調用一個方法然后使用 spring bean name 相同的 class

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

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

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

  }

使用接口投影時(在 Spring 數據存儲庫中),可以像這樣調用 static 方法:

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(); 
}

您還可以使用上述符號獲取枚舉(常量)的值。 Spring 安全檢查樣本:

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

類似的符號應該適用於其他地方。 只需記住使用 class 的完整路徑

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM