Apache Commons Configuration 验证属性文件。

6

我正在使用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来确保所有服务器符合严格的配置 - 所有配置文件,而不仅仅是应用程序特定的。 - Griff
2个回答

1
如果您向配置对象的get方法传递一个不映射到现有属性的键,那么它应该做什么?
  1. the default behavior as implemented in AbstractConfiguration is to return null if the return value is an object type.

  2. For primitive types as return values returning null (or any other special value) is not possible, so in this case a NoSuchElementException is thrown

    // 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这样的对象类型,可以更改默认行为:
如果调用setThrowExceptionOnMissing()方法并传入true作为参数,则这些方法将像它们的原始类型一样,如果无法解析传入的属性键,则抛出异常。
对于集合和数组类型,情况有点棘手,它们将返回空集合或数组。

0
我遇到了完全相同的问题,所以我制作了一个小型库,用于一次性验证整个配置。它可以根据您在配置中所需的确切规范进行定制。
它可以配置为与任何配置库一起使用,并且目前默认支持Apache Commons Config和SnakeYAML。
您可以在此处找到它以及基本使用指南:https://github.com/TTNO1/ConfigValidation4j

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接