Browse Source

Leniently accept same singleton instance if implicitly appeared

Closes gh-34427
pull/34656/head
Juergen Hoeller 10 months ago
parent
commit
94eb6006e8
  1. 12
      spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java
  2. 15
      spring-beans/src/test/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistryTests.java

12
spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistry.java

@ -368,8 +368,18 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements @@ -368,8 +368,18 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
addSingleton(beanName, singletonObject);
try {
addSingleton(beanName, singletonObject);
}
catch (IllegalStateException ex) {
// Leniently accept same instance if implicitly appeared.
Object object = this.singletonObjects.get(beanName);
if (singletonObject != object) {
throw ex;
}
}
}
}
return singletonObject;

15
spring-beans/src/test/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistryTests.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -50,10 +50,15 @@ class DefaultSingletonBeanRegistryTests { @@ -50,10 +50,15 @@ class DefaultSingletonBeanRegistryTests {
assertThat(beanRegistry.getSingleton("tb2")).isSameAs(tb2);
assertThat(tb2Flag.get()).isTrue();
assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb);
assertThat(beanRegistry.getSingleton("tb2")).isSameAs(tb2);
assertThat(beanRegistry.getSingletonCount()).isEqualTo(2);
assertThat(beanRegistry.getSingletonNames()).containsExactly("tb", "tb2");
TestBean tb3 = (TestBean) beanRegistry.getSingleton("tb3", () -> {
TestBean newTb = new TestBean();
beanRegistry.registerSingleton("tb3", newTb);
return newTb;
});
assertThat(beanRegistry.getSingleton("tb3")).isSameAs(tb3);
assertThat(beanRegistry.getSingletonCount()).isEqualTo(3);
assertThat(beanRegistry.getSingletonNames()).containsExactly("tb", "tb2", "tb3");
beanRegistry.destroySingletons();
assertThat(beanRegistry.getSingletonCount()).isZero();

Loading…
Cancel
Save