【Spring】IOC 过程中 @Autowired 如何从多个实现中确定要注入的实例bean?@Primary的作用

1 实验code

    @Autowired
    private AbClient myAbClient;

    多个实例实现了AbClient接口;
    最典型的是@EnableFeignClients Spring cloud客户端用的居多
复制代码

2 结果:org.springframework.beans.factory.support.DefaultListableBeanFactory#determinePrimaryCandidate

主要依据Bean定义是否是org.springframework.beans.factory.support.DefaultListableBeanFactory#isPrimary 来确定要保留的实例;

3 源码

	/**
	 * 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)) {  #再次拿到Bean定义决策
				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;
	}
复制代码

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享