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

And*_*nov 6 spring yaml dependency-injection spring-annotations spring-boot

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

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

但两者都没有

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

nor
app:
    map: {Countries: "countries.xlsx", CurrencyRates: "rates.xlsx"}
Run Code Online (Sandbox Code Playgroud)

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

也不

app:
    map:
      "[Countries]": countries.xslx
      "[CurrencyRates]": rates.xlsx
Run Code Online (Sandbox Code Playgroud)

(如/sf/answers/3622578641/所建议)

有效 - 我不断收到消息“自动装配依赖项注入失败;嵌套异常是 java.lang.IllegalArgumentException:无法解析占位符'

同时这也有效:

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

但我想将属性外部化

Dog*_*027 9

@ConfigurationProperties按照您链接的问题的答案之一的建议使用:

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

进而

@Autowired
@Qualifier("AppProps")
private Map<String, String> props;
Run Code Online (Sandbox Code Playgroud)

可以与配置一起使用

app:
  map:
    Countries: 'countries.xlsx'
    CurrencyRates: 'rates.xlsx'
Run Code Online (Sandbox Code Playgroud)

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

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

app:
  map: "{Countries: 'countries.xlsx', CurrencyRates: 'rates.xlsx'}"
Run Code Online (Sandbox Code Playgroud)

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