Skip to content

Commit 733cbc5

Browse files
jhoellerpinguin3245678
authored andcommitted
Leniently accept same singleton instance if implicitly appeared
Closes spring-projectsgh-34427 Signed-off-by: Vincent Potucek <[email protected]>
1 parent a46fa74 commit 733cbc5

File tree

2 files changed

+21
-6
lines changed

2 files changed

+21
-6
lines changed

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,8 +366,18 @@ public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
366366
}
367367
afterSingletonCreation(beanName);
368368
}
369+
369370
if (newSingleton) {
370-
addSingleton(beanName, singletonObject);
371+
try {
372+
addSingleton(beanName, singletonObject);
373+
}
374+
catch (IllegalStateException ex) {
375+
// Leniently accept same instance if implicitly appeared.
376+
Object object = this.singletonObjects.get(beanName);
377+
if (singletonObject != object) {
378+
throw ex;
379+
}
380+
}
371381
}
372382
}
373383
return singletonObject;

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

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2024 the original author or authors.
2+
* Copyright 2002-2025 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -50,10 +50,15 @@ void singletons() {
5050
assertThat(beanRegistry.getSingleton("tb2")).isSameAs(tb2);
5151
assertThat(tb2Flag.get()).isTrue();
5252

53-
assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb);
54-
assertThat(beanRegistry.getSingleton("tb2")).isSameAs(tb2);
55-
assertThat(beanRegistry.getSingletonCount()).isEqualTo(2);
56-
assertThat(beanRegistry.getSingletonNames()).containsExactly("tb", "tb2");
53+
TestBean tb3 = (TestBean) beanRegistry.getSingleton("tb3", () -> {
54+
TestBean newTb = new TestBean();
55+
beanRegistry.registerSingleton("tb3", newTb);
56+
return newTb;
57+
});
58+
assertThat(beanRegistry.getSingleton("tb3")).isSameAs(tb3);
59+
60+
assertThat(beanRegistry.getSingletonCount()).isEqualTo(3);
61+
assertThat(beanRegistry.getSingletonNames()).containsExactly("tb", "tb2", "tb3");
5762

5863
beanRegistry.destroySingletons();
5964
assertThat(beanRegistry.getSingletonCount()).isZero();

0 commit comments

Comments
 (0)