【问题标题】:Apache Commons Configuration validate properties fileApache Commons 配置验证属性文件
【发布时间】:2016-06-04 07:19:49
【问题描述】:

我正在使用Apache Commons Configuration 库和PropertiesConfiguration。 我的应用程序在启动后立即加载配置文件,如下所示:

public PropertiesConfiguration loadConfigFile(File configFile) throws ConfigurationNotFoundException {
        try {
            if (configFile != null && configFile.exists()) {
                config.load(configFile);
                config.setListDelimiter(';');
                config.setAutoSave(true);
                config.setReloadingStrategy(new FileChangedReloadingStrategy());
                setConfigLoaded(true);
            }
            else {
                throw new ConfigurationNotFoundException("Configuration file not found.");
            }

        } catch (ConfigurationException e) {
            logger.warn(e.getMessage());
            setDefaultConfigValues(config);
            config.setFile(configFile);
        }
        return config;
}

我的问题是,如何验证configFile,所以我可以确定该文件中没有任何属性丢失,稍后在我的代码中尝试访问属性时我不会得到NullPointerException,例如:

PropertiesConfiguration config = loadConfig(configFile);
String rootDir = config.getString("paths.download"); // I want to be sure that this property exists right at the app start

我在文档或谷歌中没有找到任何东西,只是关于 XML 验证的内容。
目标是在程序启动时向用户提供配置文件已损坏的反馈。
属性文件没有内置机制?

【问题讨论】:

  • 在典型的生产环境中,大多数人使用 puppet 或 chef 来确保所有服务器都符合严格的配置——所有配置文件,而不仅仅是特定于应用程序。

标签: java validation properties-file apache-commons-config


【解决方案1】:

如果你将一个键传递给它的一个 get 方法,但它没有映射到现有属性,那么配置对象应该做什么?

  1. 如果返回值为对象类型,则 AbstractConfiguration 中实现的默认行为是返回 null。

  2. 对于原始类型作为返回值返回 null(或任何其他特殊值)是不可能的,因此在这种情况下会抛出 NoSuchElementException

    // This will return null if no property with key "NonExistingProperty" exists
    String strValue = config.getString("NonExistingProperty");
    
    // This will throw a NoSuchElementException exception if no property with
    // key "NonExistingProperty" exists
    long longValue = config.getLong("NonExistingProperty");
    

对于 String、BigDecimal 或 BigInteger 等对象类型,可以更改此默认行为:

如果使用参数 true 调用 setThrowExceptionOnMissing() 方法,则这些方法的行为类似于它们的原始对应部分,并且如果传入的属性键无法解析,也会引发异常。

对于集合和数组类型来说,情况有点棘手,因为它们会返回空集合或数组。

【讨论】:

    猜你喜欢
    • 2011-08-31
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    相关资源
    最近更新 更多