如何使用变量名从 Java Spring 中的 application.yml 中读取值?

how to read value from application.yml in Java Spring with variable name?

我正在尝试读取特定值(在控制器 class 中),我得到了这样的信息:

@Value("${userId.site.%s}")
private String userIdSite;

但是“站点”是一个变量,它可以是一个值或另一个值。

在 Application.yml 我得到了:

userId:
  site:
    mla: 123
    mlb: 456

我怎样才能正确地做到这一点?

如果您想保留@Value 注释并可以随意将站点数据制作成地图:

userId:
   site: '{
       mla: 123,
       mlb: 456
   }'

并在您的代码中将 userIdSite 定义为地图。

@Value("#{${userId.site}}")
private Map<String, Integer> userIdSite;

然后使用您的 'variable' 从地图中获取值。另一个略有不同的替代方法是使用可以读取地图的@ConfigurationProperties 使用:

userId:
   site:
       mla: 123,
       mlb: 456