Support 'required properties' precondition
Users may now call #setRequiredProperties(String...) against the Environment (via its ConfigurablePropertyResolver interface) in order to indicate which properties must be present. Environment#validateRequiredProperties() is invoked by AbstractApplicationContext during the refresh() lifecycle to perform the actual check and a MissingRequiredPropertiesException is thrown if the precondition is not satisfied. Issue: SPR-8323
This commit is contained in:
@@ -318,6 +318,40 @@ public class PropertySourcesPropertyResolverTests {
|
||||
resolver.getPropertyAsClass("some.class", SomeType.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setRequiredProperties_andValidateRequiredProperties() {
|
||||
// no properties have been marked as required -> validation should pass
|
||||
propertyResolver.validateRequiredProperties();
|
||||
|
||||
// mark which properties are required
|
||||
propertyResolver.setRequiredProperties("foo", "bar");
|
||||
|
||||
// neither foo nor bar properties are present -> validating should throw
|
||||
try {
|
||||
propertyResolver.validateRequiredProperties();
|
||||
fail("expected validation exception");
|
||||
} catch (MissingRequiredPropertiesException ex) {
|
||||
assertThat(ex.getMessage(), equalTo(
|
||||
"The following properties were declared as required " +
|
||||
"but could not be resolved: [foo, bar]"));
|
||||
}
|
||||
|
||||
// add foo property -> validation should fail only on missing 'bar' property
|
||||
testProperties.put("foo", "fooValue");
|
||||
try {
|
||||
propertyResolver.validateRequiredProperties();
|
||||
fail("expected validation exception");
|
||||
} catch (MissingRequiredPropertiesException ex) {
|
||||
assertThat(ex.getMessage(), equalTo(
|
||||
"The following properties were declared as required " +
|
||||
"but could not be resolved: [bar]"));
|
||||
}
|
||||
|
||||
// add bar property -> validation should pass, even with an empty string value
|
||||
testProperties.put("bar", "");
|
||||
propertyResolver.validateRequiredProperties();
|
||||
}
|
||||
|
||||
static interface SomeType { }
|
||||
static class SpecificType implements SomeType { }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user