Java:Preferences API与Apache Commons Configuration的比较

6

我需要允许用户存储/加载任意数量的对象列表(假设它们可序列化)。从概念上讲,我想要一个数据模型,如下所示:

class FooBean { /* bean stuff here */ }

class FooList {
    final private Set<FooBean> items = new HashSet<FooBean>();

    public boolean add(FooBean item) { return items.add(item); }
    public boolean remove(FooBean item) { return items.remove(item); }
    public Collection<FooBean> getItems() { 
       return Collections.unmodifiableSet(items); 
    }
}

class FooStore {
    public FooStore() {
       /* something... uses Preferences or Commons Configuration */ 
    }
    public FooList load(String key) {
       /* something... retrieves a FooList associated with the key */ 
    }
    public void store(String key, FooList items) { 
       /* something... saves a FooList under the given key */
    }
}

我应该使用 Preferences API(高级偏好设置API) 还是 Commons Config?它们各自的优点是什么?

4个回答

6

commons-configuration是一个抽象层,就像许多Apache项目一样,它允许您无缝地使用首选项、LDAP存储、属性文件等。 因此,您的问题可以重写为:您是否需要更改用于存储首选项的格式?如果不需要,那么Java首选项就是正确的选择。否则,请考虑使用commons configuration的可移植性。


2

在您提供的将一组值与键关联存储的示例中,使用每个库时似乎有以下选项:

  • 首选项(Preferences) - 将其作为与键关联的字节数组存储
  • Commons配置(Commons Configuration) - 将其作为与键相关联的字符串列表存储

因此,选择可能取决于将FooBean转换为字节数组或字符串哪个更容易。

Commons配置的另一个优势是不同的后端。我曾经用它来将属性存储在数据库中。如果您想要将对象存储在用户本地机器以外的其他位置,则它是更好的选择。


1

Commons Configuration 不适合存储复杂对象结构。最好使用序列化框架。


1

通常我会选择JDK中的Preferences API,除非commons-config可以解决其他问题。

个人而言,当我使用Spring时,它有一个Property Configurer可以为我完成大部分工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接