当前位置: 首页 > 知识库问答 >
问题:

从。yaml读取的属性map与@value Spring注释的正确用法是什么

戈曾琪
2023-03-14
@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"}
app:
    map:
      "[Countries]": countries.xslx
      "[CurrencyRates]": rates.xlsx

同时,这起作用:

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

但我想将属性外部化

共有1个答案

仲和韵
2023-03-14

使用@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("#{${app.map}}")
private Map<String, String> props;
app:
  map: "{Countries: 'countries.xlsx', CurrencyRates: 'rates.xlsx'}"
 类似资料: