简体   繁体   English

如何使用spring从属性文件中加载地图

[英]how to load map from properties file with spring

I am trying to load a map from .properties file into a HashMap 我正在尝试将地图从.properties文件加载到HashMap

the properties file has the following: 属性文件具有以下内容:

try.map= one=1,\
two=2

The code: 编码:

@org.springframework.beans.factory.annotation.Value("${try.map}")
HashMap<String, String> tryMap;

And loading the property to the map results in : 并将属性加载到地图中会导致:

 java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.HashMap]: no matching editors or conversion strategy found

Any ideas how to create a mapping strategy for this? 任何想法如何为此创建映射策略?

i got this error too. 我也收到此错误。 If you want to resolve it without doing much efforts, just check your imports properly. 如果要解决此问题而无需付出太多努力,只需正确检查导入即可。 Mostly you will get this error if you import wrong files. 如果导入错误的文件,通常会出现此错误。 In case of you, I think you are importing wrong HashMap in your file. 如果您遇到这种情况,我认为您正在文件中导入错误的HashMap。 Check it should be java.util.HashMap. 检查它应该是java.util.HashMap。

There is no default converter for that. 没有默认的转换器。 So you have to write your own converter and register it to the conversationService. 因此,您必须编写自己的转换器并将其注册到sessionService。

Here an annotation-based example: 这是一个基于注释的示例:

@Bean(name="conversionService") 
public static ConversionService getConversionService(){
    ConversionServiceFactoryBean conversionServiceFactoryBean = new ConversionServiceFactoryBean();
    Set<Converter<?,?>> converters = new HashSet<Converter<?,?>>();
    converters.add(new StringToHashMapConverter());
    conversionServiceFactoryBean.setConverters(converters);
    conversionServiceFactoryBean.afterPropertiesSet();
    return conversionServiceFactoryBean.getObject();
}

The Converter: 转换器:

import java.util.HashMap;

import org.springframework.core.convert.converter.Converter;

public class StringToHashMapConverter implements Converter<String,HashMap> {

    @Override
    public HashMap convert(String paramS) {
           //do the coversion
    }

}

This works for me: 这对我有用:

try.map= {\
  one: 1,\
  two: 2\
}

The code: 编码:

@org.springframework.beans.factory.annotation.Value("#{${try.map}}")
HashMap<String, String> tryMap;

Yes, the syntax is quite odd. 是的,语法很奇怪。

This SO post has more info: How to fill HashMap from java property file with Spring @Value 该SO帖子具有更多信息: 如何使用Spring @Value从java属性文件填充HashMap。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM