Java 类org.springframework.beans.factory.NoUniqueBeanDefinitionException 实例源码

项目:lams    文件:PersistenceAnnotationBeanPostProcessor.java   
/**
 * Find a single default EntityManagerFactory in the Spring application context.
 * @return the default EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no single EntityManagerFactory in the context
 */
protected EntityManagerFactory findDefaultEntityManagerFactory(String requestingBeanName)
        throws NoSuchBeanDefinitionException {

    String[] beanNames =
            BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, EntityManagerFactory.class);
    if (beanNames.length == 1) {
        String unitName = beanNames[0];
        EntityManagerFactory emf = (EntityManagerFactory) this.beanFactory.getBean(unitName);
        if (this.beanFactory instanceof ConfigurableBeanFactory) {
            ((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName);
        }
        return emf;
    }
    else if (beanNames.length > 1) {
        throw new NoUniqueBeanDefinitionException(EntityManagerFactory.class, beanNames);
    }
    else {
        throw new NoSuchBeanDefinitionException(EntityManagerFactory.class);
    }
}
项目:spring4-understanding    文件:GenericApplicationContextTests.java   
@Test
public void getBeanForClass() {
    GenericApplicationContext ac = new GenericApplicationContext();
    ac.registerBeanDefinition("testBean", new RootBeanDefinition(String.class));
    ac.refresh();

    assertSame(ac.getBean("testBean"), ac.getBean(String.class));
    assertSame(ac.getBean("testBean"), ac.getBean(CharSequence.class));

    try {
        assertSame(ac.getBean("testBean"), ac.getBean(Object.class));
        fail("Should have thrown NoUniqueBeanDefinitionException");
    }
    catch (NoUniqueBeanDefinitionException ex) {
        // expected
    }
}
项目:spring4-understanding    文件:PersistenceAnnotationBeanPostProcessor.java   
/**
 * Find a single default EntityManagerFactory in the Spring application context.
 * @return the default EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no single EntityManagerFactory in the context
 */
protected EntityManagerFactory findDefaultEntityManagerFactory(String requestingBeanName)
        throws NoSuchBeanDefinitionException {

    String[] beanNames =
            BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, EntityManagerFactory.class);
    if (beanNames.length == 1) {
        String unitName = beanNames[0];
        EntityManagerFactory emf = (EntityManagerFactory) this.beanFactory.getBean(unitName);
        if (this.beanFactory instanceof ConfigurableBeanFactory) {
            ((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName);
        }
        return emf;
    }
    else if (beanNames.length > 1) {
        throw new NoUniqueBeanDefinitionException(EntityManagerFactory.class, beanNames);
    }
    else {
        throw new NoSuchBeanDefinitionException(EntityManagerFactory.class);
    }
}
项目:spring4-understanding    文件:DefaultListableBeanFactory.java   
/**
 * Determine the primary candidate in the given set of beans.
 * @param candidateBeans a Map of candidate names and candidate instances
 * that match the required type
 * @param requiredType the target dependency type to match against
 * @return the name of the primary candidate, or {@code null} if none found
 * @see #isPrimary(String, Object)
 */
protected String determinePrimaryCandidate(Map<String, Object> candidateBeans, Class<?> requiredType) {
    String primaryBeanName = null;
    for (Map.Entry<String, Object> entry : candidateBeans.entrySet()) {
        String candidateBeanName = entry.getKey();
        Object beanInstance = entry.getValue();
        if (isPrimary(candidateBeanName, beanInstance)) {
            if (primaryBeanName != null) {
                boolean candidateLocal = containsBeanDefinition(candidateBeanName);
                boolean primaryLocal = containsBeanDefinition(primaryBeanName);
                if (candidateLocal && primaryLocal) {
                    throw new NoUniqueBeanDefinitionException(requiredType, candidateBeans.size(),
                            "more than one 'primary' bean found among candidates: " + candidateBeans.keySet());
                }
                else if (candidateLocal) {
                    primaryBeanName = candidateBeanName;
                }
            }
            else {
                primaryBeanName = candidateBeanName;
            }
        }
    }
    return primaryBeanName;
}
项目:leopard    文件:LeopardPropertyPlaceholderConfigurer.java   
public <T> T getBean(BeanFactory beanFactory, Class<T> requiredType) throws BeansException {
    DefaultListableBeanFactory factory = (DefaultListableBeanFactory) beanFactory;
    Map<String, T> matchingBeans = factory.getBeansOfType(requiredType);
    if (matchingBeans.isEmpty()) {
        throw new NoSuchBeanDefinitionException(requiredType);
    }
    if (matchingBeans.size() == 1) {
        return matchingBeans.entrySet().iterator().next().getValue();
    }
    for (Entry<String, T> entry : matchingBeans.entrySet()) {
        T bean = entry.getValue();
        // TODO 还没有支持Bean有AOP
        Primary primary = bean.getClass().getDeclaredAnnotation(Primary.class);
        if (primary != null) {
            return bean;
        }
    }
    throw new NoUniqueBeanDefinitionException(requiredType, matchingBeans.keySet());
}
项目:spring    文件:DefaultListableBeanFactory.java   
/**
 * Determine the primary candidate in the given set of beans.
 * @param candidateBeans a Map of candidate names and candidate instances
 * that match the required type
 * @param requiredType the target dependency type to match against
 * @return the name of the primary candidate, or {@code null} if none found
 * @see #isPrimary(String, Object)
 */
protected String determinePrimaryCandidate(Map<String, Object> candidateBeans, Class<?> requiredType) {
    String primaryBeanName = null;
    for (Map.Entry<String, Object> entry : candidateBeans.entrySet()) {
        String candidateBeanName = entry.getKey();
        Object beanInstance = entry.getValue();
        if (isPrimary(candidateBeanName, beanInstance)) {
            if (primaryBeanName != null) {
                boolean candidateLocal = containsBeanDefinition(candidateBeanName);
                boolean primaryLocal = containsBeanDefinition(primaryBeanName);
                if (candidateLocal && primaryLocal) {
                    throw new NoUniqueBeanDefinitionException(requiredType, candidateBeans.size(),
                            "more than one 'primary' bean found among candidates: " + candidateBeans.keySet());
                }
                else if (candidateLocal) {
                    primaryBeanName = candidateBeanName;
                }
            }
            else {
                primaryBeanName = candidateBeanName;
            }
        }
    }
    return primaryBeanName;
}
项目:booties    文件:CustomSchedulingConfiguration.java   
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    if (properties.isEnabled()) {
        TaskScheduler taskScheduler = null;
        try {
            taskScheduler = this.beanFactory.getBean(TaskScheduler.class);
        } catch (NoUniqueBeanDefinitionException e) {
            taskScheduler = this.beanFactory.getBean("taskScheduler", TaskScheduler.class);
        } catch (NoSuchBeanDefinitionException ex) {
            log.warn("'useExistingScheduler' was configured to 'true', but we did not find any bean.");
        }
        if (taskScheduler != null) {
            log.info("register existing TaskScheduler");
            taskRegistrar.setScheduler(taskScheduler);
        } else {
            throw new BeanCreationException("Expecting a 'ConcurrentTaskScheduler' injected, but was 'null'");
        }
    } else {
        log.info("'CustomSchedulingConfiguration' is disabled, create a default - 'ConcurrentTaskScheduler'");
        this.localExecutor = Executors.newSingleThreadScheduledExecutor();
        taskRegistrar.setScheduler(new ConcurrentTaskScheduler(localExecutor));
    }
}
项目:booties    文件:AsyncExecutorConfiguration.java   
@Override
public Executor getAsyncExecutor() {
    if (properties.isEnabled()) {
        ThreadPoolTaskExecutor executor = null;
        try {
            executor = beanFactory.getBean(ThreadPoolTaskExecutor.class);
        } catch (NoUniqueBeanDefinitionException e) {
            executor = beanFactory.getBean(DEFAULT_TASK_EXECUTOR_BEAN_NAME, ThreadPoolTaskExecutor.class);
        } catch (NoSuchBeanDefinitionException ex) {
        }
        if (executor != null) {
            log.info("use default TaskExecutor ...");
            return executor;
        } else {
            throw new BeanCreationException("Expecting a 'ThreadPoolTaskExecutor' exists, but was 'null'");
        }
    } else {
        log.info(
                "'AsyncExecutorConfiguration' is disabled, so create 'SimpleAsyncTaskExecutor' with 'threadNamePrefix' - '{}'",
                properties.getThreadNamePrefix());
        return new SimpleAsyncTaskExecutor(properties.getThreadNamePrefix());
    }
}
项目:class-guard    文件:PersistenceAnnotationBeanPostProcessor.java   
/**
 * Find a single default EntityManagerFactory in the Spring application context.
 * @return the default EntityManagerFactory
 * @throws NoSuchBeanDefinitionException if there is no single EntityManagerFactory in the context
 */
protected EntityManagerFactory findDefaultEntityManagerFactory(String requestingBeanName)
        throws NoSuchBeanDefinitionException {

    String[] beanNames =
            BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, EntityManagerFactory.class);
    if (beanNames.length == 1) {
        String unitName = beanNames[0];
        EntityManagerFactory emf = (EntityManagerFactory) this.beanFactory.getBean(unitName);
        if (this.beanFactory instanceof ConfigurableBeanFactory) {
            ((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName);
        }
        return emf;
    }
    else if (beanNames.length > 1) {
        throw new NoUniqueBeanDefinitionException(EntityManagerFactory.class, beanNames);
    }
    else {
        throw new NoSuchBeanDefinitionException(EntityManagerFactory.class);
    }
}
项目:clobaframe    文件:DefaultBeanFactory.java   
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
    Assert.notNull(requiredType);

    Map<String, T> objects = getBeansOfType(requiredType);
    if (objects.isEmpty()) {
        throw new NoSuchBeanDefinitionException(requiredType);
    }

    if (objects.size() > 1) {
        throw new NoUniqueBeanDefinitionException(requiredType, objects.keySet());
                //"More than one object are assign from this class: " + requiredType.getName());
    }

    return objects.values().iterator().next();
}
项目:beetl2.0    文件:BeetlSpringViewResolver.java   
/**
 * 初始化检查GroupTemplate<br>
 * 实现InitializingBean,在Bean IOC注入结束后自动调用
 *
 * @throws NoSuchBeanDefinitionException
 *             如果未设置GroupTemplate,且Spring上下文中也没有唯一的GroupTemplate bean
 * @throws NoUniqueBeanDefinitionException
 *             如果未设置GroupTemplate,且Spring上下文中有多个GroupTemplate bean
 * @throws NoSuchFieldException
 * @throws SecurityException
 */
@Override
public void afterPropertiesSet() throws NoSuchBeanDefinitionException, NoUniqueBeanDefinitionException,
        SecurityException, NoSuchFieldException
{
    // 如果未指定groupTemplate,取上下文中唯一的GroupTemplate对象
    if (config == null)
    {
        config = getApplicationContext().getBean(BeetlGroupUtilConfiguration.class);
        this.groupTemplate = config.getGroupTemplate();
    }

    // 如果没有设置ContentType,设置个默认的
    if (getContentType() == null)
    {
        String charset = groupTemplate.getConf().getCharset();
        setContentType("text/html;charset=" + charset);
    }

}
项目:lams    文件:StaticListableBeanFactory.java   
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
    String[] beanNames = getBeanNamesForType(requiredType);
    if (beanNames.length == 1) {
        return getBean(beanNames[0], requiredType);
    }
    else if (beanNames.length > 1) {
        throw new NoUniqueBeanDefinitionException(requiredType, beanNames);
    }
    else {
        throw new NoSuchBeanDefinitionException(requiredType);
    }
}
项目:lams    文件:DefaultListableBeanFactory.java   
/**
 * Determine the primary autowire candidate in the given set of beans.
 * @param candidateBeans a Map of candidate names and candidate instances
 * that match the required type, as returned by {@link #findAutowireCandidates}
 * @param descriptor the target dependency to match against
 * @return the name of the primary candidate, or {@code null} if none found
 */
protected String determinePrimaryCandidate(Map<String, Object> candidateBeans, DependencyDescriptor descriptor) {
    String primaryBeanName = null;
    String fallbackBeanName = null;
    for (Map.Entry<String, Object> entry : candidateBeans.entrySet()) {
        String candidateBeanName = entry.getKey();
        Object beanInstance = entry.getValue();
        if (isPrimary(candidateBeanName, beanInstance)) {
            if (primaryBeanName != null) {
                boolean candidateLocal = containsBeanDefinition(candidateBeanName);
                boolean primaryLocal = containsBeanDefinition(primaryBeanName);
                if (candidateLocal == primaryLocal) {
                    throw new NoUniqueBeanDefinitionException(descriptor.getDependencyType(), candidateBeans.size(),
                            "more than one 'primary' bean found among candidates: " + candidateBeans.keySet());
                }
                else if (candidateLocal && !primaryLocal) {
                    primaryBeanName = candidateBeanName;
                }
            }
            else {
                primaryBeanName = candidateBeanName;
            }
        }
        if (primaryBeanName == null &&
                (this.resolvableDependencies.values().contains(beanInstance) ||
                        matchesBeanName(candidateBeanName, descriptor.getDependencyName()))) {
            fallbackBeanName = candidateBeanName;
        }
    }
    return (primaryBeanName != null ? primaryBeanName : fallbackBeanName);
}
项目:spring4-understanding    文件:StaticListableBeanFactory.java   
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
    String[] beanNames = getBeanNamesForType(requiredType);
    if (beanNames.length == 1) {
        return getBean(beanNames[0], requiredType);
    }
    else if (beanNames.length > 1) {
        throw new NoUniqueBeanDefinitionException(requiredType, beanNames);
    }
    else {
        throw new NoSuchBeanDefinitionException(requiredType);
    }
}
项目:spring4-understanding    文件:DefaultListableBeanFactory.java   
/**
 * Determine the candidate with the highest priority in the given set of beans. As
 * defined by the {@link org.springframework.core.Ordered} interface, the lowest
 * value has the highest priority.
 * @param candidateBeans a Map of candidate names and candidate instances
 * that match the required type
 * @param requiredType the target dependency type to match against
 * @return the name of the candidate with the highest priority,
 * or {@code null} if none found
 * @see #getPriority(Object)
 */
protected String determineHighestPriorityCandidate(Map<String, Object> candidateBeans, Class<?> requiredType) {
    String highestPriorityBeanName = null;
    Integer highestPriority = null;
    for (Map.Entry<String, Object> entry : candidateBeans.entrySet()) {
        String candidateBeanName = entry.getKey();
        Object beanInstance = entry.getValue();
        Integer candidatePriority = getPriority(beanInstance);
        if (candidatePriority != null) {
            if (highestPriorityBeanName != null) {
                if (candidatePriority.equals(highestPriority)) {
                    throw new NoUniqueBeanDefinitionException(requiredType, candidateBeans.size(),
                            "Multiple beans found with the same priority ('" + highestPriority + "') " +
                                    "among candidates: " + candidateBeans.keySet());
                }
                else if (candidatePriority < highestPriority) {
                    highestPriorityBeanName = candidateBeanName;
                    highestPriority = candidatePriority;
                }
            }
            else {
                highestPriorityBeanName = candidateBeanName;
                highestPriority = candidatePriority;
            }
        }
    }
    return highestPriorityBeanName;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:NoUniqueBeanDefinitionFailureAnalyzer.java   
@Override
protected FailureAnalysis analyze(Throwable rootFailure,
        NoUniqueBeanDefinitionException cause) {
    String consumerDescription = getConsumerDescription(rootFailure);
    if (consumerDescription == null) {
        return null;
    }
    String[] beanNames = extractBeanNames(cause);
    if (beanNames == null) {
        return null;
    }
    StringBuilder message = new StringBuilder();
    message.append(String.format("%s required a single bean, but %d were found:%n",
            consumerDescription, beanNames.length));
    for (String beanName : beanNames) {
        try {
            BeanDefinition beanDefinition = this.beanFactory
                    .getMergedBeanDefinition(beanName);
            if (StringUtils.hasText(beanDefinition.getFactoryMethodName())) {
                message.append(String.format("\t- %s: defined by method '%s' in %s%n",
                        beanName, beanDefinition.getFactoryMethodName(),
                        beanDefinition.getResourceDescription()));
            }
            else {
                message.append(String.format("\t- %s: defined in %s%n", beanName,
                        beanDefinition.getResourceDescription()));
            }
        }
        catch (NoSuchBeanDefinitionException ex) {
            message.append(String.format(
                    "\t- %s: a programmatically registered singleton", beanName));
        }

    }
    return new FailureAnalysis(message.toString(),
            "Consider marking one of the beans as @Primary, updating the consumer to"
                    + " accept multiple beans, or using @Qualifier to identify the"
                    + " bean that should be consumed",
            cause);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:NoUniqueBeanDefinitionFailureAnalyzer.java   
private String[] extractBeanNames(NoUniqueBeanDefinitionException cause) {
    if (cause.getMessage().indexOf("but found") > -1) {
        return StringUtils.commaDelimitedListToStringArray(cause.getMessage()
                .substring(cause.getMessage().lastIndexOf(":") + 1).trim());
    }
    return null;
}
项目:spring    文件:StaticListableBeanFactory.java   
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
    String[] beanNames = getBeanNamesForType(requiredType);
    if (beanNames.length == 1) {
        return getBean(beanNames[0], requiredType);
    }
    else if (beanNames.length > 1) {
        throw new NoUniqueBeanDefinitionException(requiredType, beanNames);
    }
    else {
        throw new NoSuchBeanDefinitionException(requiredType);
    }
}
项目:spring    文件:DefaultListableBeanFactory.java   
/**
 * Determine the candidate with the highest priority in the given set of beans. As
 * defined by the {@link org.springframework.core.Ordered} interface, the lowest
 * value has the highest priority.
 * @param candidateBeans a Map of candidate names and candidate instances
 * that match the required type
 * @param requiredType the target dependency type to match against
 * @return the name of the candidate with the highest priority,
 * or {@code null} if none found
 * @see #getPriority(Object)
 */
protected String determineHighestPriorityCandidate(Map<String, Object> candidateBeans, Class<?> requiredType) {
    String highestPriorityBeanName = null;
    Integer highestPriority = null;
    for (Map.Entry<String, Object> entry : candidateBeans.entrySet()) {
        String candidateBeanName = entry.getKey();
        Object beanInstance = entry.getValue();
        Integer candidatePriority = getPriority(beanInstance);
        if (candidatePriority != null) {
            if (highestPriorityBeanName != null) {
                if (candidatePriority.equals(highestPriority)) {
                    throw new NoUniqueBeanDefinitionException(requiredType, candidateBeans.size(),
                            "Multiple beans found with the same priority ('" + highestPriority + "') " +
                                    "among candidates: " + candidateBeans.keySet());
                }
                else if (candidatePriority < highestPriority) {
                    highestPriorityBeanName = candidateBeanName;
                    highestPriority = candidatePriority;
                }
            }
            else {
                highestPriorityBeanName = candidateBeanName;
                highestPriority = candidatePriority;
            }
        }
    }
    return highestPriorityBeanName;
}
项目:spring-boot-concourse    文件:NoUniqueBeanDefinitionFailureAnalyzer.java   
@Override
protected FailureAnalysis analyze(Throwable rootFailure,
        NoUniqueBeanDefinitionException cause) {
    String consumerDescription = getConsumerDescription(rootFailure);
    if (consumerDescription == null) {
        return null;
    }
    String[] beanNames = extractBeanNames(cause);
    if (beanNames == null) {
        return null;
    }
    StringBuilder message = new StringBuilder();
    message.append(String.format("%s required a single bean, but %d were found:%n",
            consumerDescription, beanNames.length));
    for (String beanName : beanNames) {
        try {
            BeanDefinition beanDefinition = this.beanFactory
                    .getMergedBeanDefinition(beanName);
            if (StringUtils.hasText(beanDefinition.getFactoryMethodName())) {
                message.append(String.format("\t- %s: defined by method '%s' in %s%n",
                        beanName, beanDefinition.getFactoryMethodName(),
                        beanDefinition.getResourceDescription()));
            }
            else {
                message.append(String.format("\t- %s: defined in %s%n", beanName,
                        beanDefinition.getResourceDescription()));
            }
        }
        catch (NoSuchBeanDefinitionException ex) {
            message.append(String.format(
                    "\t- %s: a programmatically registered singleton", beanName));
        }

    }
    return new FailureAnalysis(message.toString(),
            "Consider marking one of the beans as @Primary, updating the consumer to"
                    + " accept multiple beans, or using @Qualifier to identify the"
                    + " bean that should be consumed",
            cause);
}
项目:spring-boot-concourse    文件:NoUniqueBeanDefinitionFailureAnalyzer.java   
private String[] extractBeanNames(NoUniqueBeanDefinitionException cause) {
    if (cause.getMessage().indexOf("but found") > -1) {
        return StringUtils.commaDelimitedListToStringArray(cause.getMessage()
                .substring(cause.getMessage().lastIndexOf(":") + 1).trim());
    }
    return null;
}
项目:kc-rice    文件:DefaultListableBeanFactory.java   
/**
 * Determine the primary autowire candidate in the given set of beans.
 * @param candidateBeans a Map of candidate names and candidate instances
 * that match the required type, as returned by {@link #findAutowireCandidates}
 * @param descriptor the target dependency to match against
 * @return the name of the primary candidate, or {@code null} if none found
 */
protected String determinePrimaryCandidate(Map<String, Object> candidateBeans, DependencyDescriptor descriptor) {
    String primaryBeanName = null;
    String fallbackBeanName = null;
    for (Map.Entry<String, Object> entry : candidateBeans.entrySet()) {
        String candidateBeanName = entry.getKey();
        Object beanInstance = entry.getValue();
        if (isPrimary(candidateBeanName, beanInstance)) {
            if (primaryBeanName != null) {
                boolean candidateLocal = containsBeanDefinition(candidateBeanName);
                boolean primaryLocal = containsBeanDefinition(primaryBeanName);
                if (candidateLocal == primaryLocal) {
                    throw new NoUniqueBeanDefinitionException(descriptor.getDependencyType(), candidateBeans.size(),
                            "more than one 'primary' bean found among candidates: " + candidateBeans.keySet());
                }
                else if (candidateLocal && !primaryLocal) {
                    primaryBeanName = candidateBeanName;
                }
            }
            else {
                primaryBeanName = candidateBeanName;
            }
        }
        if (primaryBeanName == null &&
                (this.resolvableDependencies.values().contains(beanInstance) ||
                        matchesBeanName(candidateBeanName, descriptor.getDependencyName()))) {
            fallbackBeanName = candidateBeanName;
        }
    }
    return (primaryBeanName != null ? primaryBeanName : fallbackBeanName);
}
项目:spring-boot-zalando-stups-tokens    文件:AccessTokensBean.java   
protected void configureScheduler(AccessTokensBuilder builder) {
    if (accessTokensBeanProperties.isUseExistingScheduler()) {
        ScheduledExecutorService scheduledExecutorService = null;
        try {
            scheduledExecutorService = this.beanFactory.getBean(ScheduledExecutorService.class);
            builder.existingExecutorService(scheduledExecutorService);
        } catch (NoUniqueBeanDefinitionException e) {
            scheduledExecutorService = this.beanFactory.getBean("scheduledExecutorService",
                    ScheduledExecutorService.class);
            builder.existingExecutorService(scheduledExecutorService);
        } catch (NoSuchBeanDefinitionException ex) {
            logger.warn("'useExistingScheduler' was configured to 'true', but we did not find any bean.");
        }
    }
}
项目:class-guard    文件:StaticListableBeanFactory.java   
public <T> T getBean(Class<T> requiredType) throws BeansException {
    String[] beanNames = getBeanNamesForType(requiredType);
    if (beanNames.length == 1) {
        return getBean(beanNames[0], requiredType);
    }
    else if (beanNames.length > 1) {
        throw new NoUniqueBeanDefinitionException(requiredType, beanNames);
    }
    else {
        throw new NoSuchBeanDefinitionException(requiredType);
    }
}
项目:class-guard    文件:DefaultListableBeanFactory.java   
/**
 * Determine the primary autowire candidate in the given set of beans.
 * @param candidateBeans a Map of candidate names and candidate instances
 * that match the required type, as returned by {@link #findAutowireCandidates}
 * @param descriptor the target dependency to match against
 * @return the name of the primary candidate, or {@code null} if none found
 */
protected String determinePrimaryCandidate(Map<String, Object> candidateBeans, DependencyDescriptor descriptor) {
    String primaryBeanName = null;
    String fallbackBeanName = null;
    for (Map.Entry<String, Object> entry : candidateBeans.entrySet()) {
        String candidateBeanName = entry.getKey();
        Object beanInstance = entry.getValue();
        if (isPrimary(candidateBeanName, beanInstance)) {
            if (primaryBeanName != null) {
                boolean candidateLocal = containsBeanDefinition(candidateBeanName);
                boolean primaryLocal = containsBeanDefinition(primaryBeanName);
                if (candidateLocal == primaryLocal) {
                    throw new NoUniqueBeanDefinitionException(descriptor.getDependencyType(), candidateBeans.size(),
                            "more than one 'primary' bean found among candidates: " + candidateBeans.keySet());
                }
                else if (candidateLocal && !primaryLocal) {
                    primaryBeanName = candidateBeanName;
                }
            }
            else {
                primaryBeanName = candidateBeanName;
            }
        }
        if (primaryBeanName == null &&
                (this.resolvableDependencies.values().contains(beanInstance) ||
                        matchesBeanName(candidateBeanName, descriptor.getDependencyName()))) {
            fallbackBeanName = candidateBeanName;
        }
    }
    return (primaryBeanName != null ? primaryBeanName : fallbackBeanName);
}
项目:spring    文件:DependencyDescriptor.java   
/**
 * Resolve the specified not-unique scenario: by default,
 * throwing a {@link NoUniqueBeanDefinitionException}.
 * <p>Subclasses may override this to select one of the instances or
 * to opt out with no result at all through returning {@code null}.
 * @param type the requested bean type
 * @param matchingBeans a map of bean names and corresponding bean
 * instances which have been pre-selected for the given type
 * (qualifiers etc already applied)
 * @return a bean instance to proceed with, or {@code null} for none
 * @throws BeansException in case of the not-unique scenario being fatal
 * @since 4.3
 */
public Object resolveNotUnique(Class<?> type, Map<String, Object> matchingBeans) throws BeansException {
    throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet());
}