使用@Value Spring 注释从.yaml 读取的属性 映射的正确用法是什么

What is the correct use of the property map read from .yaml with @Value Spring Annotation

我已经通过以下方式从 Spring 引导应用程序中的某些 .yaml 读取的地图中注入了属性:

@Value("#{${app.map}}")
private Map<String, String> indexesMap = new HashMap<>();

但都不是

app:
    map: {Countries: 'countries.xlsx', CurrencyRates: 'rates.xlsx'} 
    //note values in single quotes  

nor
app:
    map: {Countries: "countries.xlsx", CurrencyRates: "rates.xlsx"}

(如 https://www.baeldung.com/spring-value-annotation 所述)

也不

app:
    map:
      "[Countries]": countries.xslx
      "[CurrencyRates]": rates.xlsx

(如 所建议)

有效 - 我不断收到消息 'Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder'

同时这有效:

@Value("#{{Countries: 'countries.xlsx', CurrencyRates: 'rates.xlsx'}}")
private Map<String, String> indexesMap = new HashMap<>();

但我想外部化属性

使用 @ConfigurationProperties,如您链接的问题的其中一个答案中所建议的那样:

@Bean(name="AppProps")
@ConfigurationProperties(prefix="app.map")
public Map<String, String> appProps() {
    return new HashMap();
}

然后

@Autowired
@Qualifier("AppProps")
private Map<String, String> props;

将与配置一起工作

app:
  map:
    Countries: 'countries.xlsx'
    CurrencyRates: 'rates.xlsx'

编辑:@Value 注释也有效,但您必须将其视为 YAML 中的字符串:

@Value("#{${app.map}}")
private Map<String, String> props;

app:
  map: "{Countries: 'countries.xlsx', CurrencyRates: 'rates.xlsx'}"

注意地图值周围的引号。在这种情况下,显然 Spring 从字符串中解析出来。