覆盖由 apache common PropertyConfiguration 加载的重复 属性 键

Overwrite duplicate property key loaded by apache common PropertyConfiguration

我一直在寻找一个 属性 for apache commons 属性 配置,它可以覆盖 属性 文件中存在的重复键,而不是附加属性并像列表一样处理,但找不到任何这样的 属性。是否有相同的解决方法?

默认情况下,Apache commons 属性 配置将仅加载在属性 file.As 中找到的第一个键值对,据我所知,它不提供任何 属性 您正在查找的内容for.This 出现行为是因为 PropertiesConfigurations 调用 resolveContainerStore(key) 方法。默认实现是这样的

protected Object resolveContainerStore(String key)
    {
        Object value = getProperty(key);
        if (value != null)
        {
            if (value instanceof Collection)
            {
                Collection collection = (Collection) value;
                value = collection.isEmpty() ? null : collection.iterator().next();
            }
            else if (value.getClass().isArray() && Array.getLength(value) > 0)
            {
                value = Array.get(value, 0);
            }
        }

        return value;
    }

在此实现中,它 returns 从值列表中为给定键找到的第一个值,即 value = Array.get(value, 0);

如果您希望覆盖属性以便返回上次加载的 属性,则可以覆盖默认实现。这是我对上述功能的实现。

@Override        
protected Object resolveContainerStore(String key) {
                Object value = getProperty(key);
                if (value != null) {
                    if (value instanceof Collection) {
                        Collection collection = (Collection) value;
                        Iterator iterator = collection.iterator();
                        value = null;
                        while (iterator.hasNext()) {
                            value = iterator.next();
                        }
                    } else if (value.getClass().isArray() && Array.getLength(value) > 0) {
                        value = Array.get(value, Array.getLength(value) - 1);
                    }
                }
                return value;
            }