Avoid instantiation of non-selected beans in BeanFactoryAnnotationUtils.qualifiedBeanOfType

Issue: SPR-13741
This commit is contained in:
Juergen Hoeller 2015-11-30 20:13:03 +01:00
parent 7104076e19
commit 8ed2c470be
1 changed files with 6 additions and 8 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2015 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,7 +17,6 @@
package org.springframework.beans.factory.annotation; package org.springframework.beans.factory.annotation;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Map;
import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.BeanFactoryUtils;
@ -77,20 +76,19 @@ public class BeanFactoryAnnotationUtils {
* @throws NoSuchBeanDefinitionException if no matching bean of type {@code T} found * @throws NoSuchBeanDefinitionException if no matching bean of type {@code T} found
*/ */
private static <T> T qualifiedBeanOfType(ConfigurableListableBeanFactory bf, Class<T> beanType, String qualifier) { private static <T> T qualifiedBeanOfType(ConfigurableListableBeanFactory bf, Class<T> beanType, String qualifier) {
Map<String, T> candidateBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(bf, beanType); String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType);
T matchingBean = null; String matchingBean = null;
for (Map.Entry<String, T> entry : candidateBeans.entrySet()) { for (String beanName : candidateBeans) {
String beanName = entry.getKey();
if (isQualifierMatch(qualifier, beanName, bf)) { if (isQualifierMatch(qualifier, beanName, bf)) {
if (matchingBean != null) { if (matchingBean != null) {
throw new NoSuchBeanDefinitionException(qualifier, "No unique " + beanType.getSimpleName() + throw new NoSuchBeanDefinitionException(qualifier, "No unique " + beanType.getSimpleName() +
" bean found for qualifier '" + qualifier + "'"); " bean found for qualifier '" + qualifier + "'");
} }
matchingBean = entry.getValue(); matchingBean = beanName;
} }
} }
if (matchingBean != null) { if (matchingBean != null) {
return matchingBean; return bf.getBean(matchingBean, beanType);
} }
else if (bf.containsBean(qualifier)) { else if (bf.containsBean(qualifier)) {
// Fallback: target bean at least found by bean name - probably a manually registered singleton. // Fallback: target bean at least found by bean name - probably a manually registered singleton.