2010-02-23 77 views
6

我需要允许用户存储/加载任意数量的对象列表(假设它们是可序列化的)。从概念上我要像java:Preferences API与Apache Commons配置

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 APICommons Config?每个的优点是什么?

回答

1

我通常会使用Preferences API,它是JDK的一部分,除非有其他问题由commons-config解决。

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

6

好吧,commons-configuration像许多apache项目一样,是一个抽象层,允许用户无缝地使用首选项,ldap存储区,属性文件等等。 因此,您的问题可以改写为:您是否需要更改用于存储偏好的格式?如果不是的话,那么java偏好就是要走的路。在其他地方,考虑公共配置的可移植性。

2

鉴于你存储一组与键关联的例子中,你似乎有以下几种选择使用每个库

  • 首时 - 店与关键
  • 共享相关的字节数组配置 - 存储为与密钥关联的字符串列表

因此,可以选择将FooBean转换为字节数组还是String。

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

1

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

相关问题