org.springframework.beans.factory.NoUniqueBeanDefinitionException Java Examples

The following examples show how to use org.springframework.beans.factory.NoUniqueBeanDefinitionException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultListableBeanFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: BeetlSpringViewResolver.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 初始化检查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);
	}

}
 
Example #3
Source File: AsyncExecutorConfiguration.java    From booties with Apache License 2.0 6 votes vote down vote up
@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());
    }
}
 
Example #4
Source File: CustomSchedulingConfiguration.java    From booties with Apache License 2.0 6 votes vote down vote up
@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));
    }
}
 
Example #5
Source File: GridSpringResourceInjectionSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @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);
}
 
Example #6
Source File: DefaultListableBeanFactory.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: PersistenceAnnotationBeanPostProcessor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example #8
Source File: GenericApplicationContextTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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
	}
}
 
Example #9
Source File: BeanFactoryAnnotationUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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!");
	}
}
 
Example #10
Source File: DefaultListableBeanFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: BeanFactoryAnnotationUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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!");
	}
}
 
Example #12
Source File: GenericApplicationContextTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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
	}
}
 
Example #13
Source File: GenericApplicationContextTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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
	}
}
 
Example #14
Source File: BeanFactoryAnnotationUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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!");
	}
}
 
Example #15
Source File: NoUniqueBeanDefinitionExceptionDemo.java    From geekbang-lessons with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #16
Source File: DefaultListableBeanFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #17
Source File: StaticListableBeanFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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);
	}
}
 
Example #18
Source File: ScheduledTaskConfigurationTest.java    From bugsnag-java with MIT License 5 votes vote down vote up
@Test
public void findExecutorByName() throws NoSuchFieldException, IllegalAccessException {
    ScheduledExecutorService expected = Executors.newScheduledThreadPool(4);
    Throwable exc = new NoUniqueBeanDefinitionException(ScheduledExecutorService.class);
    when(context.getBean(ScheduledExecutorService.class)).thenThrow(exc);
    when(context.getBean("taskScheduler", ScheduledExecutorService.class))
            .thenReturn(expected);

    configuration.configureTasks(registrar);
    TaskScheduler scheduler = registrar.getScheduler();
    assertTrue(scheduler instanceof ConcurrentTaskScheduler);
    assertEquals(expected, accessField(scheduler, "scheduledExecutor"));
}
 
Example #19
Source File: ScheduledTaskConfigurationTest.java    From bugsnag-java with MIT License 5 votes vote down vote up
@Test
public void findSchedulerByName() throws NoSuchFieldException, IllegalAccessException {
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    Throwable exc = new NoUniqueBeanDefinitionException(TaskScheduler.class);
    when(context.getBean(TaskScheduler.class)).thenThrow(exc);
    when(context.getBean("taskScheduler", TaskScheduler.class)).thenReturn(scheduler);

    configuration.configureTasks(registrar);
    assertNull(registrar.getScheduler());
    Object errorHandler = accessField(scheduler, "errorHandler");
    assertTrue(errorHandler instanceof BugsnagScheduledTaskExceptionHandler);
}
 
Example #20
Source File: ScheduledTaskBeanLocatorTest.java    From bugsnag-java with MIT License 5 votes vote down vote up
@Test
public void findExecutorByName() {
    ScheduledExecutorService expected = Executors.newScheduledThreadPool(4);
    Throwable exc = new NoUniqueBeanDefinitionException(ScheduledExecutorService.class);
    when(context.getBean(ScheduledExecutorService.class)).thenThrow(exc);
    when(context.getBean("taskScheduler", ScheduledExecutorService.class))
            .thenReturn(expected);
    assertEquals(expected, beanLocator.resolveScheduledExecutorService());
}
 
Example #21
Source File: ScheduledTaskBeanLocatorTest.java    From bugsnag-java with MIT License 5 votes vote down vote up
@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());
}
 
Example #22
Source File: StaticListableBeanFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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);
	}
}
 
Example #23
Source File: PoseidonLegoSetTest.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example #24
Source File: DefaultListableBeanFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #25
Source File: DefaultListableBeanFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #26
Source File: StaticListableBeanFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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);
	}
}
 
Example #27
Source File: DefaultListableBeanFactory.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #28
Source File: StaticListableBeanFactory.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@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);
	}
}
 
Example #29
Source File: DefaultListableBeanFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #30
Source File: SpringExtensionFactoryTest.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetExtensionByTypeMultiple() {
    try {
        springExtensionFactory.getExtension(DemoService.class, "beanname-not-exist");
    } catch (Exception e) {
        e.printStackTrace();
        Assert.assertTrue(e instanceof NoUniqueBeanDefinitionException);
    }
}