【问题标题】:java: Preferences API vs. Apache Commons Configurationjava:首选项 API 与 Apache Commons 配置
【发布时间】:2011-01-20 06:17:27
【问题描述】:

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

这样的数据模型
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?各有什么优势?

【问题讨论】:

    标签: java configuration apache-commons


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

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

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            猜你喜欢
            • 2011-08-31
            • 1970-01-01
            • 1970-01-01
            • 2019-01-29
            • 2011-12-11
            • 2013-03-05
            • 2013-02-26
            • 2016-12-18
            • 2018-07-25
            相关资源
            最近更新 更多