【问题标题】:What is the correct use of the property map read from .yaml with @Value Spring Annotation使用@Value Spring Annotation 从.yaml 读取的属性映射的正确用法是什么
【发布时间】:2019-09-06 23:27:59
【问题描述】:

我已通过以下方式从 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 中所述)

也没有

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

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

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

同时这也有效:

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

但我想将属性外部化

【问题讨论】:

    标签: spring spring-boot dependency-injection yaml spring-annotations


    【解决方案1】:

    使用@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 将其从字符串中解析出来。

    【讨论】:

      猜你喜欢
      • 2020-08-08
      • 1970-01-01
      • 2019-08-08
      • 2016-01-26
      • 2018-03-16
      • 2014-10-10
      • 2013-12-15
      • 1970-01-01
      • 2017-07-09
      相关资源
      最近更新 更多