Java 属性文件验证
Java properties file validation
我的 Java 应用程序在启动时加载一个属性文件,其中包含键值对。我可以成功设置和检索预期的属性。
但是,就目前的情况而言,属性文件可以包含我想放入其中的任何 属性 名称。我希望能够将属性限制为特定的集合,其中一些是强制性的,另一些是可选的。
我可以根据有效集手动检查每个加载的 属性,但我想知道是否有更优雅的方法来执行此操作。例如。或许可以通过某种方式来声明预期的 mandatory/optional 属性,以便在加载属性文件时,如果检测到无效或缺失的 属性,则会抛出异常。类似于 boost::program_options
在 C++ 中提供的那种东西。
I can manually check each loaded property against a valid set but I
was wondering if there was a more elegant way to do this. E.g. perhaps
some way to declare the expected mandatory/optional properties, so
that when the properties file is loaded, an exception is thrown if an
invalid or missing property is detected.
JDK (java.util.Properties) 的内置 API 不提供这种验证。
但是,实现您自己的 ConfigLoader
class 应该不难。您的 class 可以包装 java.util.Properties
,并在加载后验证数据。例如,您可以维护一个强制和可选密钥列表(硬编码或外部加载),然后根据这些列表检查已加载密钥的列表。
您可能会找到一些执行此操作的实现,但由于验证本身无论如何都会特定于您的需求,其余部分相当简单,我认为不值得寻找现有的解决方案。
由于 Properties
已经是一个简单的可迭代结构,我将只对该对象执行验证。以下是必需与可选的简单验证。
public static void testProps(Properties props, Set<String> required, Set<String> optional) {
int requiredCount=0;
Enumeration keys = props.keys();
while (keys.hasMoreElements()) {
String key=(String) keys.nextElement();
if (required.contains(key)) {
requiredCount++;
} else if (!optional.contains(key)) {
throw new IllegalStateException("Unauthorized key : " + key);
}
}
if (requiredCount<required.size()) {
for (String requiredKey : required) {
if (!props.containsKey(requiredKey)) {
throw new IllegalStateException("Missing required key : " + requiredKey);
}
}
}
}
我的 Java 应用程序在启动时加载一个属性文件,其中包含键值对。我可以成功设置和检索预期的属性。
但是,就目前的情况而言,属性文件可以包含我想放入其中的任何 属性 名称。我希望能够将属性限制为特定的集合,其中一些是强制性的,另一些是可选的。
我可以根据有效集手动检查每个加载的 属性,但我想知道是否有更优雅的方法来执行此操作。例如。或许可以通过某种方式来声明预期的 mandatory/optional 属性,以便在加载属性文件时,如果检测到无效或缺失的 属性,则会抛出异常。类似于 boost::program_options
在 C++ 中提供的那种东西。
I can manually check each loaded property against a valid set but I was wondering if there was a more elegant way to do this. E.g. perhaps some way to declare the expected mandatory/optional properties, so that when the properties file is loaded, an exception is thrown if an invalid or missing property is detected.
JDK (java.util.Properties) 的内置 API 不提供这种验证。
但是,实现您自己的 ConfigLoader
class 应该不难。您的 class 可以包装 java.util.Properties
,并在加载后验证数据。例如,您可以维护一个强制和可选密钥列表(硬编码或外部加载),然后根据这些列表检查已加载密钥的列表。
您可能会找到一些执行此操作的实现,但由于验证本身无论如何都会特定于您的需求,其余部分相当简单,我认为不值得寻找现有的解决方案。
由于 Properties
已经是一个简单的可迭代结构,我将只对该对象执行验证。以下是必需与可选的简单验证。
public static void testProps(Properties props, Set<String> required, Set<String> optional) {
int requiredCount=0;
Enumeration keys = props.keys();
while (keys.hasMoreElements()) {
String key=(String) keys.nextElement();
if (required.contains(key)) {
requiredCount++;
} else if (!optional.contains(key)) {
throw new IllegalStateException("Unauthorized key : " + key);
}
}
if (requiredCount<required.size()) {
for (String requiredKey : required) {
if (!props.containsKey(requiredKey)) {
throw new IllegalStateException("Missing required key : " + requiredKey);
}
}
}
}