In order to override a property and then to roll it back:
protected void overrideProperties(Map<String, String> overrideMap) {
log.info("Overriding properties = {}", overrideMap);
Environment env = appContext.getEnvironment();
if (env instanceof ConfigurableEnvironment) {
ConfigurableEnvironment confEnv = (ConfigurableEnvironment) env;
MutablePropertySources sources = confEnv.getPropertySources();
// removing in case rollback was not done
if (sources.contains(TEST_RESOURCE_PROPERTIES_OVERRIDE_NAME)) {
sources.remove(TEST_RESOURCE_PROPERTIES_OVERRIDE_NAME);
}
Properties overrides = new Properties();
overrides.putAll(overrideMap);
sources.addFirst(new PropertiesPropertySource(TEST_RESOURCE_PROPERTIES_OVERRIDE_NAME, overrides));
// this triggers changes in beans annotated with @ConfigurationProperties and updates @Value fields
appContext.publishEvent(new EnvironmentChangeEvent(overrideMap.keySet()));
}
// this should never happen
else {
log.info("Unable to override properties as Environment is not of type ConfigurableEnvironment");
}
}
protected void rollbackOverriddenProperties(Map<String, String> overrideMap) {
log.info("Rolling back properties = {}", overrideMap);
Environment env = appContext.getEnvironment();
if (env instanceof ConfigurableEnvironment) {
ConfigurableEnvironment confEnv = (ConfigurableEnvironment) env;
MutablePropertySources sources = confEnv.getPropertySources();
sources.remove(TEST_RESOURCE_PROPERTIES_OVERRIDE_NAME);
// this triggers changes in beans annotated with @ConfigurationProperties and updates @Value fields
appContext.publishEvent(new EnvironmentChangeEvent(overrideMap.keySet()));
}
// this should never happen
else {
log.info("Unable to rollback overridden properties as Environment is not of type ConfigurableEnvironment");
}
}