Skip to content

Commit e89f18b

Browse files
committed
DefaultListableBeanFactory defensively handles BeanDefinition access in getBean(Class)
Issue: SPR-10542 (cherry picked from commit 9d3d6d5)
1 parent 76a3e6e commit e89f18b

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ public <T> T getBean(Class<T> requiredType) throws BeansException {
261261
if (beanNames.length > 1) {
262262
ArrayList<String> autowireCandidates = new ArrayList<String>();
263263
for (String beanName : beanNames) {
264-
if (getBeanDefinition(beanName).isAutowireCandidate()) {
264+
if (!containsBeanDefinition(beanName) || getBeanDefinition(beanName).isAutowireCandidate()) {
265265
autowireCandidates.add(beanName);
266266
}
267267
}

spring-context/src/test/java/org/springframework/context/support/GenericApplicationContextTests.java

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2010 the original author or authors.
2+
* Copyright 2002-2014 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.
@@ -18,7 +18,11 @@
1818

1919
import org.junit.Test;
2020

21+
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
2122
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
23+
import org.springframework.beans.factory.support.RootBeanDefinition;
24+
25+
import static org.junit.Assert.*;
2226

2327
/**
2428
* @author Juergen Hoeller
@@ -28,9 +32,27 @@ public class GenericApplicationContextTests {
2832

2933
@Test
3034
public void nullBeanRegistration() {
31-
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
32-
bf.registerSingleton("nullBean", null);
33-
new GenericApplicationContext(bf).refresh();
35+
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
36+
bf.registerSingleton("nullBean", null);
37+
new GenericApplicationContext(bf).refresh();
38+
}
39+
40+
@Test
41+
public void getBeanForClass() {
42+
GenericApplicationContext ac = new GenericApplicationContext();
43+
ac.registerBeanDefinition("testBean", new RootBeanDefinition(String.class));
44+
ac.refresh();
45+
46+
assertSame(ac.getBean("testBean"), ac.getBean(String.class));
47+
assertSame(ac.getBean("testBean"), ac.getBean(CharSequence.class));
48+
49+
try {
50+
assertSame(ac.getBean("testBean"), ac.getBean(Object.class));
51+
fail("Should have thrown NoUniqueBeanDefinitionException");
52+
}
53+
catch (NoUniqueBeanDefinitionException ex) {
54+
// expected
55+
}
3456
}
3557

3658
}

0 commit comments

Comments
 (0)