Java Apache Commons配置验证属性文件
我正在使用带有Java Apache Commons配置验证属性文件,java,validation,properties-file,apache-commons-config,Java,Validation,Properties File,Apache Commons Config,我正在使用带有属性配置的apachecommons配置库。 我的应用程序在启动后立即加载配置文件,如下所示: public PropertiesConfiguration loadConfigFile(File configFile) throws ConfigurationNotFoundException { try { if (configFile != null && configFile.exists()) {
属性配置的apachecommons配置
库。
我的应用程序在启动后立即加载配置文件,如下所示:
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
我在文档或google中没有找到任何内容,只是找到了一些关于XML验证的内容。
目标是在程序启动时向用户提供配置文件已损坏的反馈。
属性文件没有内置机制?如果您将一个键传递给一个未映射到现有属性的get方法,配置对象应该怎么做
AbstractConfiguration中实现的默认行为是,如果返回值是对象类型,则返回null
对于基元类型,作为返回值返回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等对象类型,可以更改此默认行为:
如果调用setThroweExceptionOnMissing()方法时参数为true,则这些方法的行为将与其基本计数器部分类似,并且如果无法解析传入的属性键,也会引发异常
收集和数组类型的情况并不复杂,因为它们将返回空的收集或数组。在典型的生产环境中,大多数人使用puppet或chef来确保所有服务器都符合严格的配置——所有配置文件,而不仅仅是特定于应用程序的配置文件。