小编典典

如何使用Spring @Value从Java属性文件填充HashMap

spring

是否可以使用Spring @Value将值从属性文件映射到HashMap。

目前,我有这样的事情,映射一个值不是问题。但是我需要在HashMap到期中映射自定义值。这样的事情可能吗?

@Service
@PropertySource(value = "classpath:my_service.properties")
public class SomeServiceImpl implements SomeService {


    @Value("#{conf['service.cache']}")
    private final boolean useCache = false;

    @Value("#{conf['service.expiration.[<custom name>]']}")
    private final HashMap<String, String> expirations = new HashMap<String, String>();

属性文件:“ my_service.properties”

service.cache=true
service.expiration.name1=100
service.expiration.name2=20

是否可以像这样的键映射:值集

  • name1 = 100

  • name2 = 20


阅读 1804

收藏
2020-04-12

共2个答案

小编典典

你可以使用类似于SPEL json的语法在属性文件中编写一个简单的映射或列表映射。

simple.map={'KEY1': 'value1', 'KEY2': 'value3', 'KEY3': 'value5'}

map.of.list={\
  'KEY1': {'value1','value2'}, \
  'KEY2': {'value3','value4'}, \
  'KEY3': {'value5'} \
 }

我使用\多行属性来提高可读性

然后,在Java中,你可以@Value像这样自动访问和解析它。

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

@Value("#{${map.of.list}}")
Map<String, List<String>> mapOfList;

在此处${simple.map}@Value从属性文件获取以下字符串:

"{'KEY1': 'value1', 'KEY2': 'value3', 'KEY3': 'value5'}"

然后,将其评估为好像已内联

@Value("#{{'KEY1': 'value1', 'KEY2': 'value3', 'KEY3': 'value5'}}")
2020-04-12
小编典典

在Spring配置中注册属性文件:

<util:properties id="myProp" location="classpath:my.properties"/>

然后创建组件:

@Component("PropertyMapper")
public class PropertyMapper {

    @Autowired
    ApplicationContext applicationContext;

    public HashMap<String, Object> startWith(String qualifier, String startWith) {
        return startWith(qualifier, startWith, false);
    }

    public HashMap<String, Object> startWith(String qualifier, String startWith, boolean removeStartWith) {
        HashMap<String, Object> result = new HashMap<String, Object>();

        Object obj = applicationContext.getBean(qualifier);
        if (obj instanceof Properties) {
            Properties mobileProperties = (Properties)obj;

            if (mobileProperties != null) {
                for (Entry<Object, Object> e : mobileProperties.entrySet()) {
                    Object oKey = e.getKey();
                    if (oKey instanceof String) {
                        String key = (String)oKey;
                        if (((String) oKey).startsWith(startWith)) {
                            if (removeStartWith) 
                                key = key.substring(startWith.length());
                            result.put(key, e.getValue());
                        }
                    }
                }
            }
        }

        return result;
    }
}

当我想将所有以specifix值开头的属性映射到带有@Value注释的HashMap时:

@Service
public class MyServiceImpl implements MyService {

    @Value("#{PropertyMapper.startWith('myProp', 'service.expiration.', true)}")
    private HashMap<String, Object> portalExpirations;
2020-04-12