2010-02-23 76 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不適合存儲複雜的對象結構。你最好使用序列化框架。

相關問題