Java 从属性文件中读取 Map 并使用 spring 注释 @Value 加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20120494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:18:14  来源:igfitidea点击:

Reading a Map from properties file and load with spring annotation @Value

javaspring

提问by Abdullah

I have a list of (key/value) need to be populated to a map on a spring bean:

我有一个(键/值)列表需要填充到 spring bean 上的映射:

dmin.details.fieldsMap=name,Abdullah,\
             street,Zayed,\
             phone,+201020102010
dmin.details.fieldsMap=name,Abdullah,\
             street,Zayed,\
             phone,+201020102010

It's working fine with me using a list as below:

使用以下列表对我来说效果很好:

property:

财产:

dmin.details.fields=Abdullah,Zayed,+201020102010

dmin.details.fields=阿卜杜拉,扎耶德,+201020102010

Calling:

调用:

@Value("#{'${dmin.details.fields}'.split(',')}")
private List<String> fields;

Could anyone advise if this is doable in Spring?

谁能建议这在Spring中是否可行?

采纳答案by Vladimir Prudnikov

application.properties:

应用程序属性:

property.map={first:value, second:value}

then in Java code you can:

然后在 Java 代码中,您可以:

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

回答by Abdullah

As I didn't find any way in spring to read the property as a Map, I had to fill the map myself using the list filled by spring as below :

由于我在 spring 中没有找到任何方法将属性作为地图读取,因此我必须使用 spring 填充的列表自己填充地图,如下所示:

@Value("#{'${dmin.details.fields}'.split(',')}")
private List<String> fields;

private Map<String, String> fieldsMap;

@PostConstruct
public void init() {
    fieldsMap = new HashMap<String, String>();
    if (fields != null && fields.size() != 0) {
        for (String field : fields) {
            String[] splittedField = field.split(",");
            fieldsMap.put(splittedField[0], splittedField[1]);
        }
    }
}

回答by Hari Rao

I found a slightly different case and explaining that below, in case if somebody is looking for it.

我发现了一个稍微不同的案例并在下面解释,以防万一有人在寻找它。

  1. I had trade_id_date={'123WC':'20100125', '234W':'20100125', 1689332:'20100125'} in properties file
  2. Below in a java class

    @Value("#{${trade_id_date}}") private Map tradeIdDateMap;

  1. 我在属性文件中有 trade_id_date={'123WC':'20100125', '234W':'20100125', 1689332:'20100125'}
  2. 下面是一个java类

    @Value("#{${trade_id_date}}") 私有映射 tradeIdDateMap;

If you do not enclose the left hand side in single quotes if it is alphanumeric then you will get

如果您不将左侧用单引号括起来,如果它是字母数字,那么您将得到

Expression parsing failed; nested exception is org.springframework.expression.spel.SpelParseException
@0: EL1044E: Unexpectedly ran out of input
  1. So make sure you enclose that in single quotes
  1. 因此,请确保将其括在单引号中