Apache Commons 配置验证属性文件

问题描述 投票:0回答:2

我正在使用

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 验证的一些内容。
目标是在程序启动时向用户提供配置文件已损坏的反馈。
没有内置的属性文件机制?

java validation properties-file apache-commons-config
2个回答
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() 方法,这些方法的行为将类似于它们的原始对应部分,并且如果无法解析传入的属性键,也会抛出异常。

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


0
投票

我遇到了完全相同的问题,所以我制作了一个小型库来立即验证整个配置。它可以进行定制,以适应您在配置中所需的确切规范。
它可以配置为与任何配置库一起使用,目前默认支持 Apache Commons Config 和 SnakeYAML。

可以在这里找到它以及基本使用指南:https://github.com/TTNO1/ConfigValidation4j

© www.soinside.com 2019 - 2024. All rights reserved.