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

2024-01-10

我通过以下方式从 Spring Boot 应用程序中的某些 .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 https://www.baeldung.com/spring-value-annotation)

nor

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

(如建议的https://stackoverflow.com/a/51751123/2566304 https://stackoverflow.com/a/51751123/2566304)

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

同时这也有效:

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

但我想将属性外部化


Use @ConfigurationProperties,正如您链接的问题的答案之一所建议的:

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

and then

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

可以与配置一起使用

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

EDIT: @Value注释也可以工作,但是您必须将其视为 YAML 中的字符串:

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

and

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐