Skip to content

Commit 6ef1e41

Browse files
committed
Add typesafe method to get generic bean by name with type reference
Fix GH-34687 Signed-off-by: Yanming Zhou <[email protected]>
1 parent 8c4b30a commit 6ef1e41

File tree

5 files changed

+121
-5
lines changed

5 files changed

+121
-5
lines changed

spring-beans/src/main/java/org/springframework/beans/factory/BeanFactory.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
package org.springframework.beans.factory;
1818

19+
import java.lang.reflect.Type;
20+
1921
import org.jspecify.annotations.Nullable;
2022

2123
import org.springframework.beans.BeansException;
@@ -100,6 +102,7 @@
100102
* @author Rod Johnson
101103
* @author Juergen Hoeller
102104
* @author Chris Beams
105+
* @author Yanming Zhou
103106
* @since 13 April 2001
104107
* @see BeanNameAware#setBeanName
105108
* @see BeanClassLoaderAware#setBeanClassLoader
@@ -175,6 +178,37 @@ public interface BeanFactory {
175178
*/
176179
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
177180

181+
/**
182+
* Return an instance, which may be shared or independent, of the specified bean.
183+
* <p>Behaves the same as {@link #getBean(String)}, but provides a measure of type
184+
* safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the
185+
* required type. This means that ClassCastException can't be thrown on casting
186+
* the result correctly, as can happen with {@link #getBean(String)}.
187+
* <p>Translates aliases back to the corresponding canonical bean name.
188+
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
189+
* @param name the name of the bean to retrieve
190+
* @param typeReference the reference to obtain type the bean must match
191+
* @return an instance of the bean.
192+
* Note that the return value will never be {@code null}. In case of a stub for
193+
* {@code null} from a factory method having been resolved for the requested bean, a
194+
* {@code BeanNotOfRequiredTypeException} against the NullBean stub will be raised.
195+
* Consider using {@link #getBeanProvider(Class)} for resolving optional dependencies.
196+
* @throws NoSuchBeanDefinitionException if there is no such bean definition
197+
* @throws BeanNotOfRequiredTypeException if the bean is not of the required type
198+
* @throws BeansException if the bean could not be created
199+
* @see #getBean(String, Class)
200+
* @since 7.0
201+
*/
202+
@SuppressWarnings("unchecked")
203+
default <T> T getBean(String name, ParameterizedTypeReference<T> typeReference) throws BeansException {
204+
Object bean = getBean(name);
205+
Type requiredType = typeReference.getType();
206+
if (!ResolvableType.forType(requiredType).isInstance(bean)) {
207+
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
208+
}
209+
return (T) bean;
210+
}
211+
178212
/**
179213
* Return an instance, which may be shared or independent, of the specified bean.
180214
* <p>Allows for specifying explicit constructor arguments / factory method arguments,

spring-beans/src/main/java/org/springframework/beans/factory/BeanNotOfRequiredTypeException.java

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616

1717
package org.springframework.beans.factory;
1818

19+
import java.lang.reflect.ParameterizedType;
20+
import java.lang.reflect.Type;
21+
1922
import org.springframework.beans.BeansException;
2023
import org.springframework.util.ClassUtils;
2124

@@ -24,6 +27,7 @@
2427
*
2528
* @author Rod Johnson
2629
* @author Juergen Hoeller
30+
* @author Yanming Zhou
2731
*/
2832
@SuppressWarnings("serial")
2933
public class BeanNotOfRequiredTypeException extends BeansException {
@@ -37,6 +41,8 @@ public class BeanNotOfRequiredTypeException extends BeansException {
3741
/** The offending type. */
3842
private final Class<?> actualType;
3943

44+
/** The required generic type. */
45+
private final Type requiredGenericType;
4046

4147
/**
4248
* Create a new BeanNotOfRequiredTypeException.
@@ -46,11 +52,32 @@ public class BeanNotOfRequiredTypeException extends BeansException {
4652
* the expected type
4753
*/
4854
public BeanNotOfRequiredTypeException(String beanName, Class<?> requiredType, Class<?> actualType) {
49-
super("Bean named '" + beanName + "' is expected to be of type '" + ClassUtils.getQualifiedName(requiredType) +
55+
this(beanName, (Type) requiredType, actualType);
56+
}
57+
58+
/**
59+
* Create a new BeanNotOfRequiredTypeException.
60+
* @param beanName the name of the bean requested
61+
* @param requiredType the required type
62+
* @param actualType the actual type returned, which did not match
63+
* the expected type
64+
* @since 7.0
65+
*/
66+
public BeanNotOfRequiredTypeException(String beanName, Type requiredType, Class<?> actualType) {
67+
super("Bean named '" + beanName + "' is expected to be of type '" + requiredType.getTypeName() +
5068
"' but was actually of type '" + ClassUtils.getQualifiedName(actualType) + "'");
5169
this.beanName = beanName;
52-
this.requiredType = requiredType;
70+
this.requiredGenericType = requiredType;
5371
this.actualType = actualType;
72+
if (requiredType instanceof Class<?> requiredClass) {
73+
this.requiredType = requiredClass;
74+
}
75+
else if (requiredType instanceof ParameterizedType parameterizedType) {
76+
this.requiredType = (Class<?>) parameterizedType.getRawType();
77+
}
78+
else {
79+
throw new IllegalArgumentException(requiredType + " is not supported");
80+
}
5481
}
5582

5683

@@ -68,6 +95,14 @@ public Class<?> getRequiredType() {
6895
return this.requiredType;
6996
}
7097

98+
/**
99+
* Return the expected generic type for the bean.
100+
* @since 7.0
101+
*/
102+
public Type getRequiredGenericType() {
103+
return this.requiredGenericType;
104+
}
105+
71106
/**
72107
* Return the actual type of the instance found.
73108
*/

spring-beans/src/main/kotlin/org/springframework/beans/factory/BeanFactoryExtensions.kt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,21 +24,22 @@ import org.springframework.core.ResolvableType
2424
* This extension is not subject to type erasure and retains actual generic type arguments.
2525
*
2626
* @author Sebastien Deleuze
27+
* @author Yanming Zhou
2728
* @since 5.0
2829
*/
2930
inline fun <reified T : Any> BeanFactory.getBean(): T =
3031
getBeanProvider<T>().getObject()
3132

3233
/**
3334
* Extension for [BeanFactory.getBean] providing a `getBean<Foo>("foo")` variant.
34-
* Like the original Java method, this extension is subject to type erasure.
35+
* This extension is not subject to type erasure and retains actual generic type arguments.
3536
*
3637
* @see BeanFactory.getBean(String, Class<T>)
3738
* @author Sebastien Deleuze
3839
* @since 5.0
3940
*/
4041
inline fun <reified T : Any> BeanFactory.getBean(name: String): T =
41-
getBean(name, T::class.java)
42+
getBean(name, (object : ParameterizedTypeReference<T>() {}))
4243

4344
/**
4445
* Extension for [BeanFactory.getBean] providing a `getBean<Foo>(arg1, arg2)` variant.

spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@
7979
import org.springframework.beans.testfixture.beans.factory.DummyFactory;
8080
import org.springframework.core.MethodParameter;
8181
import org.springframework.core.Ordered;
82+
import org.springframework.core.ParameterizedTypeReference;
8283
import org.springframework.core.ResolvableType;
8384
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
8485
import org.springframework.core.annotation.Order;
@@ -1682,6 +1683,29 @@ void getBeanByTypeWithAmbiguity() {
16821683
lbf.getBean(TestBean.class));
16831684
}
16841685

1686+
@Test
1687+
void getBeanByNameWithTypeReference() {
1688+
RootBeanDefinition bd1 = new RootBeanDefinition(StringTemplate.class);
1689+
RootBeanDefinition bd2 = new RootBeanDefinition(NumberTemplate.class);
1690+
lbf.registerBeanDefinition("bd1", bd1);
1691+
lbf.registerBeanDefinition("bd2", bd2);
1692+
1693+
Template<String> stringTemplate = lbf.getBean("bd1", new ParameterizedTypeReference<>() {});
1694+
Template<Number> numberTemplate = lbf.getBean("bd2", new ParameterizedTypeReference<>() {});
1695+
1696+
assertThat(stringTemplate).isInstanceOf(StringTemplate.class);
1697+
assertThat(numberTemplate).isInstanceOf(NumberTemplate.class);
1698+
1699+
assertThatExceptionOfType(BeanNotOfRequiredTypeException.class)
1700+
.isThrownBy(() -> lbf.getBean("bd2", new ParameterizedTypeReference<Template<String>>() {}))
1701+
.satisfies(ex -> {
1702+
assertThat(ex.getBeanName()).isEqualTo("bd2");
1703+
assertThat(ex.getRequiredType()).isEqualTo(Template.class);
1704+
assertThat(ex.getActualType()).isEqualTo(NumberTemplate.class);
1705+
assertThat(ex.getRequiredGenericType().toString()).endsWith("Template<java.lang.String>");
1706+
});
1707+
}
1708+
16851709
@Test
16861710
void getBeanByTypeWithPrimary() {
16871711
RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class);
@@ -3872,4 +3896,16 @@ public Class<?> getObjectType() {
38723896
}
38733897
}
38743898

3899+
private static class Template<T> {
3900+
3901+
}
3902+
3903+
private static class StringTemplate extends Template<String> {
3904+
3905+
}
3906+
3907+
private static class NumberTemplate extends Template<Number> {
3908+
3909+
}
3910+
38753911
}

spring-beans/src/test/kotlin/org/springframework/beans/factory/BeanFactoryExtensionsTests.kt

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import io.mockk.mockk
2121
import io.mockk.verify
2222
import org.assertj.core.api.Assertions.assertThat
2323
import org.junit.jupiter.api.Test
24+
import org.springframework.core.ParameterizedTypeReference
2425
import org.springframework.core.ResolvableType
2526

2627
/**
@@ -53,7 +54,16 @@ class BeanFactoryExtensionsTests {
5354
fun `getBean with String and reified type parameters`() {
5455
val name = "foo"
5556
bf.getBean<Foo>(name)
56-
verify { bf.getBean(name, Foo::class.java) }
57+
verify { bf.getBean(name, ofType<ParameterizedTypeReference<Foo>>()) }
58+
}
59+
60+
@Test
61+
fun `getBean with String and reified generic type parameters`() {
62+
val name = "foo"
63+
val foo = listOf(Foo())
64+
every { bf.getBean(name, ofType<ParameterizedTypeReference<List<Foo>>>()) } returns foo
65+
assertThat(bf.getBean<List<Foo>>("foo")).isSameAs(foo)
66+
verify { bf.getBean(name, ofType<ParameterizedTypeReference<List<Foo>>>()) }
5767
}
5868

5969
@Test

0 commit comments

Comments
 (0)