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

下面列出了怎么用org.springframework.beans.factory.NoUniqueBeanDefinitionException的API类实例代码及写法,或者点击链接到github查看源代码。

@Test
public void getBeanForClass() {
	GenericApplicationContext ac = new GenericApplicationContext();
	ac.registerBeanDefinition("testBean", new RootBeanDefinition(String.class));
	ac.refresh();

	assertEquals("", ac.getBean("testBean"));
	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
	}
}
 
/**
 * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier
 * (e.g. {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier).
 * @param bf the factory to get the target bean from
 * @param beanType the type of bean to retrieve
 * @param qualifier the qualifier for selecting between multiple bean matches
 * @return the matching bean of type {@code T} (never {@code null})
 */
private static <T> T qualifiedBeanOfType(ListableBeanFactory bf, Class<T> beanType, String qualifier) {
	String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType);
	String matchingBean = null;
	for (String beanName : candidateBeans) {
		if (isQualifierMatch(qualifier::equals, beanName, bf)) {
			if (matchingBean != null) {
				throw new NoUniqueBeanDefinitionException(beanType, matchingBean, beanName);
			}
			matchingBean = beanName;
		}
	}
	if (matchingBean != null) {
		return bf.getBean(matchingBean, beanType);
	}
	else if (bf.containsBean(qualifier)) {
		// Fallback: target bean at least found by bean name - probably a manually registered singleton.
		return bf.getBean(qualifier, beanType);
	}
	else {
		throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() +
				" bean found for qualifier '" + qualifier + "' - neither qualifier match nor bean name match!");
	}
}
 
/**
 * Determine the primary candidate in the given set of beans.
 * @param candidates a Map of candidate names and candidate instances
 * (or candidate classes if not created yet) 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)
 */
@Nullable
protected String determinePrimaryCandidate(Map<String, Object> candidates, Class<?> requiredType) {
	String primaryBeanName = null;
	for (Map.Entry<String, Object> entry : candidates.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, candidates.size(),
							"more than one 'primary' bean found among candidates: " + candidates.keySet());
				}
				else if (candidateLocal) {
					primaryBeanName = candidateBeanName;
				}
			}
			else {
				primaryBeanName = candidateBeanName;
			}
		}
	}
	return primaryBeanName;
}
 
public static void main(String[] args) {
    // 创建 BeanFactory 容器
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    // 将当前类 NoUniqueBeanDefinitionExceptionDemo 作为配置类(Configuration Class)
    applicationContext.register(NoUniqueBeanDefinitionExceptionDemo.class);
    // 启动应用上下文
    applicationContext.refresh();

    try {
        // 由于 Spring 应用上下文存在两个 String 类型的 Bean,通过单一类型查找会抛出异常
        applicationContext.getBean(String.class);
    } catch (NoUniqueBeanDefinitionException e) {
        System.err.printf(" Spring 应用上下文存在%d个 %s 类型的 Bean,具体原因:%s%n",
                e.getNumberOfBeansFound(),
                String.class.getName(),
                e.getMessage());
    }

    // 关闭应用上下文
    applicationContext.close();
}
 
@Test
public void getBeanForClass() {
	GenericApplicationContext ac = new GenericApplicationContext();
	ac.registerBeanDefinition("testBean", new RootBeanDefinition(String.class));
	ac.refresh();

	assertEquals("", ac.getBean("testBean"));
	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
	}
}
 
/**
 * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier
 * (e.g. {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier).
 * @param bf the factory to get the target bean from
 * @param beanType the type of bean to retrieve
 * @param qualifier the qualifier for selecting between multiple bean matches
 * @return the matching bean of type {@code T} (never {@code null})
 */
private static <T> T qualifiedBeanOfType(ListableBeanFactory bf, Class<T> beanType, String qualifier) {
	String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType);
	String matchingBean = null;
	for (String beanName : candidateBeans) {
		if (isQualifierMatch(qualifier::equals, beanName, bf)) {
			if (matchingBean != null) {
				throw new NoUniqueBeanDefinitionException(beanType, matchingBean, beanName);
			}
			matchingBean = beanName;
		}
	}
	if (matchingBean != null) {
		return bf.getBean(matchingBean, beanType);
	}
	else if (bf.containsBean(qualifier)) {
		// Fallback: target bean at least found by bean name - probably a manually registered singleton.
		return bf.getBean(qualifier, beanType);
	}
	else {
		throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() +
				" bean found for qualifier '" + qualifier + "' - neither qualifier match nor bean name match!");
	}
}
 
/**
 * Determine the primary candidate in the given set of beans.
 * @param candidates a Map of candidate names and candidate instances
 * (or candidate classes if not created yet) 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)
 */
@Nullable
protected String determinePrimaryCandidate(Map<String, Object> candidates, Class<?> requiredType) {
	String primaryBeanName = null;
	for (Map.Entry<String, Object> entry : candidates.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, candidates.size(),
							"more than one 'primary' bean found among candidates: " + candidates.keySet());
				}
				else if (candidateLocal) {
					primaryBeanName = candidateBeanName;
				}
			}
			else {
				primaryBeanName = candidateBeanName;
			}
		}
	}
	return primaryBeanName;
}
 
源代码8 项目: lams   文件: BeanFactoryAnnotationUtils.java
/**
 * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier
 * (e.g. {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier).
 * @param bf the BeanFactory to get the target bean from
 * @param beanType the type of bean to retrieve
 * @param qualifier the qualifier for selecting between multiple bean matches
 * @return the matching bean of type {@code T} (never {@code null})
 */
private static <T> T qualifiedBeanOfType(ConfigurableListableBeanFactory bf, Class<T> beanType, String qualifier) {
	String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType);
	String matchingBean = null;
	for (String beanName : candidateBeans) {
		if (isQualifierMatch(qualifier, beanName, bf)) {
			if (matchingBean != null) {
				throw new NoUniqueBeanDefinitionException(beanType, matchingBean, beanName);
			}
			matchingBean = beanName;
		}
	}
	if (matchingBean != null) {
		return bf.getBean(matchingBean, beanType);
	}
	else if (bf.containsBean(qualifier)) {
		// Fallback: target bean at least found by bean name - probably a manually registered singleton.
		return bf.getBean(qualifier, beanType);
	}
	else {
		throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() +
				" bean found for qualifier '" + qualifier + "' - neither qualifier match nor bean name match!");
	}
}
 
源代码9 项目: lams   文件: DefaultListableBeanFactory.java
/**
 * Determine the primary candidate in the given set of beans.
 * @param candidates a Map of candidate names and candidate instances
 * (or candidate classes if not created yet) 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> candidates, Class<?> requiredType) {
	String primaryBeanName = null;
	for (Map.Entry<String, Object> entry : candidates.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, candidates.size(),
							"more than one 'primary' bean found among candidates: " + candidates.keySet());
				}
				else if (candidateLocal) {
					primaryBeanName = candidateBeanName;
				}
			}
			else {
				primaryBeanName = candidateBeanName;
			}
		}
	}
	return primaryBeanName;
}
 
@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
	}
}
 
/**
 * 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);
	}
}
 
/**
 * 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;
}
 
/**
 * @throws Exception If failed.
 */
@Test
public void testClosureFieldByResourceClassWithMultipleBeans() throws Exception {
    IgniteConfiguration anotherCfg = new IgniteConfiguration();
    anotherCfg.setIgniteInstanceName("anotherGrid");

    Ignite anotherGrid = IgniteSpring.start(anotherCfg, new ClassPathXmlApplicationContext(
        "/org/apache/ignite/internal/processors/resource/spring-resource-with-duplicate-beans.xml"));

    assertError(new IgniteCallable<Object>() {
        @SpringResource(resourceClass = DummyResourceBean.class)
        private transient DummyResourceBean dummyRsrcBean;

        @Override public Object call() throws Exception {
            assertNotNull(dummyRsrcBean);

            return null;
        }
    }, anotherGrid, NoUniqueBeanDefinitionException.class, "No qualifying bean of type " +
        "'org.apache.ignite.internal.processors.resource.GridSpringResourceInjectionSelfTest$DummyResourceBean'" +
        " available: expected single matching bean but found 2:");

    G.stop("anotherGrid", false);
}
 
源代码14 项目: 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));
    }
}
 
源代码15 项目: 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());
    }
}
 
源代码16 项目: 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);
	}

}
 
源代码17 项目: dubbo-2.6.5   文件: SpringExtensionFactoryTest.java
@Test
public void testGetExtensionByTypeMultiple() {
    try {
        springExtensionFactory.getExtension(DemoService.class, "beanname-not-exist");
    } catch (Exception e) {
        e.printStackTrace();
        Assert.assertTrue(e instanceof NoUniqueBeanDefinitionException);
    }
}
 
@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);
	}
}
 
/**
 * Determine the candidate with the highest priority in the given set of beans.
 * <p>Based on {@code @javax.annotation.Priority}. As defined by the related
 * {@link org.springframework.core.Ordered} interface, the lowest value has
 * the highest priority.
 * @param candidates a Map of candidate names and candidate instances
 * (or candidate classes if not created yet) 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)
 */
@Nullable
protected String determineHighestPriorityCandidate(Map<String, Object> candidates, Class<?> requiredType) {
	String highestPriorityBeanName = null;
	Integer highestPriority = null;
	for (Map.Entry<String, Object> entry : candidates.entrySet()) {
		String candidateBeanName = entry.getKey();
		Object beanInstance = entry.getValue();
		if (beanInstance != null) {
			Integer candidatePriority = getPriority(beanInstance);
			if (candidatePriority != null) {
				if (highestPriorityBeanName != null) {
					if (candidatePriority.equals(highestPriority)) {
						throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(),
								"Multiple beans found with the same priority ('" + highestPriority +
								"') among candidates: " + candidates.keySet());
					}
					else if (candidatePriority < highestPriority) {
						highestPriorityBeanName = candidateBeanName;
						highestPriority = candidatePriority;
					}
				}
				else {
					highestPriorityBeanName = candidateBeanName;
					highestPriority = candidatePriority;
				}
			}
		}
	}
	return highestPriorityBeanName;
}
 
@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);
	}
}
 
/**
 * Determine the candidate with the highest priority in the given set of beans.
 * <p>Based on {@code @javax.annotation.Priority}. As defined by the related
 * {@link org.springframework.core.Ordered} interface, the lowest value has
 * the highest priority.
 * @param candidates a Map of candidate names and candidate instances
 * (or candidate classes if not created yet) 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)
 */
@Nullable
protected String determineHighestPriorityCandidate(Map<String, Object> candidates, Class<?> requiredType) {
	String highestPriorityBeanName = null;
	Integer highestPriority = null;
	for (Map.Entry<String, Object> entry : candidates.entrySet()) {
		String candidateBeanName = entry.getKey();
		Object beanInstance = entry.getValue();
		if (beanInstance != null) {
			Integer candidatePriority = getPriority(beanInstance);
			if (candidatePriority != null) {
				if (highestPriorityBeanName != null) {
					if (candidatePriority.equals(highestPriority)) {
						throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(),
								"Multiple beans found with the same priority ('" + highestPriority +
								"') among candidates: " + candidates.keySet());
					}
					else if (candidatePriority < highestPriority) {
						highestPriorityBeanName = candidateBeanName;
						highestPriority = candidatePriority;
					}
				}
				else {
					highestPriorityBeanName = candidateBeanName;
					highestPriority = candidatePriority;
				}
			}
		}
	}
	return highestPriorityBeanName;
}
 
@PostConstruct
public void setupSmsVerificationCodeSender() {
    if (senders.size() > 2) {
        throw new NoUniqueBeanDefinitionException(SmsVerificationCodeSender.class, senders.keySet());
    }
    SmsVerificationCodeSender sender = senders.get("smsVerificationSender");
    if (sender.getClass().isAssignableFrom(DefaultSmsVerificationCodeSender.class)) {
        DefaultSmsVerificationCodeSender defaultSmsVerificationCodeSender = (DefaultSmsVerificationCodeSender) sender;
        defaultSmsVerificationCodeSender.setTarget(findTarget());
    }
}
 
源代码23 项目: 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);
	}
}
 
源代码24 项目: lams   文件: DefaultListableBeanFactory.java
/**
 * Determine the candidate with the highest priority in the given set of beans.
 * <p>Based on {@code @javax.annotation.Priority}. As defined by the related
 * {@link org.springframework.core.Ordered} interface, the lowest value has
 * the highest priority.
 * @param candidates a Map of candidate names and candidate instances
 * (or candidate classes if not created yet) 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> candidates, Class<?> requiredType) {
	String highestPriorityBeanName = null;
	Integer highestPriority = null;
	for (Map.Entry<String, Object> entry : candidates.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, candidates.size(),
							"Multiple beans found with the same priority ('" + highestPriority +
							"') among candidates: " + candidates.keySet());
				}
				else if (candidatePriority < highestPriority) {
					highestPriorityBeanName = candidateBeanName;
					highestPriority = candidatePriority;
				}
			}
			else {
				highestPriorityBeanName = candidateBeanName;
				highestPriority = candidatePriority;
			}
		}
	}
	return highestPriorityBeanName;
}
 
源代码25 项目: blog_demos   文件: 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);
	}
}
 
源代码26 项目: blog_demos   文件: 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);
}
 
@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);
	}
}
 
/**
 * 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;
}
 
源代码29 项目: Poseidon   文件: PoseidonLegoSetTest.java
@Test(expected = NoUniqueBeanDefinitionException.class)
public void testInjectableDataSourceMultipleDependency() throws Throwable {
    when(context.getBean(any(Class.class))).thenThrow(NoUniqueBeanDefinitionException.class);
    TestLegoSet legoSet = new TestLegoSet();
    legoSet.setContext(context);
    legoSet.init();

    try {
        legoSet.getDataSource(CallableNameHelper.versionedName(PROPER_INJECTABLE_DS_NAME, "4.1.6"), request);
    } catch (Exception e) {
        throw e.getCause();
    }
}
 
@Test
public void findSchedulerByName() {
    ThreadPoolTaskScheduler expected = new ThreadPoolTaskScheduler();
    Throwable exc = new NoUniqueBeanDefinitionException(TaskScheduler.class);
    when(context.getBean(TaskScheduler.class)).thenThrow(exc);
    when(context.getBean("taskScheduler", TaskScheduler.class)).thenReturn(expected);
    assertEquals(expected, beanLocator.resolveTaskScheduler());
}
 
 类方法
 同包方法