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

新手上路,请多包涵

是否可以使用 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

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

  • 名称 1 = 100

  • 名称 2 = 20

原文由 d-sauer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 561
2 个回答

我在上一篇文章的启发下提出了一个解决方案。

在 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;
    }
}

当我想将所有以特定值开头的属性映射到 HashMap 时,使用 @Value 注释:

 @Service
public class MyServiceImpl implements MyService {

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

原文由 d-sauer 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 SPEL json-like 语法在属性文件中编写一个简单的地图或列表地图。

 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'}}")

您可以在 官方文档 中了解更多信息

原文由 Marc Bouvier 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题