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还是Commons Config?各有什么优势?

4

4 回答 4

6

嗯,commons-configuration 就像许多 apache 项目一样,是一个抽象层,允许人们无缝地使用首选项、ldap 存储、属性文件等。因此,您的问题可以按原样重写:您是否需要更改用于存储偏好的格式?如果没有,Java 首选项是要走的路。在其他地方,请考虑公共配置的可移植性。

于 2010-03-08T15:35:13.740 回答
2

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

  • 首选项 - 存储为与键关联的字节数组
  • Commons Configuration - 存储为与键关联的字符串列表

因此,选择可以归结为将 FooBean 转换为字节数组还是字符串更容易。

Commons Configuration 的另一个优点是不同的后端。我用它来将属性存储在数据库中。如果您想将对象存储在用户本地计算机以外的其他地方,那将是更好的选择。

于 2010-03-08T22:19:46.360 回答
1

我通常会使用作为 JDK 一部分的 Preferences API,除非存在 commons-config 以其他方式解决的问题。

就我个人而言,当我使用 spring 时,它有一个属性配置器,它可以为我完成大部分工作。

于 2010-03-08T15:24:01.650 回答
1

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

于 2010-11-30T21:13:08.717 回答