Apache Commons 配置验证属性文件

len*_*nny 6 java validation properties-file apache-commons-config

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

AGd*_*dev 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");
    
    Run Code Online (Sandbox Code Playgroud)

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

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

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