Destroy and initialize beans within the correct context. Fixes #1158 (#1160)

Co-authored-by: Ryan Baxter <524254+ryanjbaxter@users.noreply.github.com>
This commit is contained in:
Ryan Baxter
2022-10-25 09:05:18 -04:00
committed by GitHub
parent 6a03d2b201
commit 86c44de855
2 changed files with 30 additions and 23 deletions

View File

@@ -89,30 +89,37 @@ public class ConfigurationPropertiesRebinder
if (!this.beans.getBeanNames().contains(name)) {
return false;
}
if (this.applicationContext != null) {
try {
Object bean = this.applicationContext.getBean(name);
if (AopUtils.isAopProxy(bean)) {
bean = ProxyUtils.getTargetObject(bean);
}
if (bean != null) {
// TODO: determine a more general approach to fix this.
// see https://github.com/spring-cloud/spring-cloud-commons/issues/571
if (getNeverRefreshable().contains(bean.getClass().getName())) {
return false; // ignore
ApplicationContext appContext = this.applicationContext;
while (appContext != null) {
if (appContext.containsLocalBean(name)) {
try {
Object bean = appContext.getBean(name);
if (AopUtils.isAopProxy(bean)) {
bean = ProxyUtils.getTargetObject(bean);
}
this.applicationContext.getAutowireCapableBeanFactory().destroyBean(bean);
this.applicationContext.getAutowireCapableBeanFactory().initializeBean(bean, name);
return true;
if (bean != null) {
// TODO: determine a more general approach to fix this.
// see
// https://github.com/spring-cloud/spring-cloud-commons/issues/571
if (getNeverRefreshable().contains(bean.getClass().getName())) {
return false; // ignore
}
appContext.getAutowireCapableBeanFactory().destroyBean(bean);
appContext.getAutowireCapableBeanFactory().initializeBean(bean, name);
return true;
}
}
catch (RuntimeException e) {
this.errors.put(name, e);
throw e;
}
catch (Exception e) {
this.errors.put(name, e);
throw new IllegalStateException("Cannot rebind to " + name, e);
}
}
catch (RuntimeException e) {
this.errors.put(name, e);
throw e;
}
catch (Exception e) {
this.errors.put(name, e);
throw new IllegalStateException("Cannot rebind to " + name, e);
else {
appContext = appContext.getParent();
}
}
return false;

View File

@@ -71,12 +71,12 @@ public class ConfigurationPropertiesRebinderIntegrationTests {
@Test
@DirtiesContext
public void testRefreshInParent() throws Exception {
then(this.config.getName()).isEqualTo("main");
then(this.config.getName()).isEqualTo("parent");
// Change the dynamic property source...
TestPropertyValues.of("config.name=foo").applyTo(this.environment);
// ...and then refresh, so the bean is re-initialized:
this.rebinder.rebind();
then(this.config.getName()).isEqualTo("foo");
then(this.config.getName()).isEqualTo("parent");
}
@Test