Spring Candidate Bean Type策略不应在检查限定符之前实例化给定类型的所有bean

时间:2014-11-27 19:00:29

标签: java spring

拥有一个具有多个数据库的应用程序和一个自定义EntityManager范围。

我认为Spring会为一些Type创建所有bean的condidates,然后才能过滤掉合格的bean。

所以在我的情况下,它打开所有emfs,即使我只需要打开一个!

debuging让我找到导致问题的部分代码: org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils

/**
  * 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).
 */
private static <T> T qualifiedBeanOfType(ConfigurableListableBeanFactory bf, Class<T> beanType, String qualifier) {    
    Map<String, T> candidateBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(bf, beanType);
 -> Spring is looking for all bean condidate with the given Type before testing the qualifier
        T matchingBean = null;
        for (String beanName : candidateBeans.keySet()) {
            if (isQualifierMatch(qualifier, beanName, bf)) {
            ........
            }
        }
    }

然后是创作部分

    public <T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
                throws BeansException {

        String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
        Map<String, T> result = new LinkedHashMap<String, T>(beanNames.length);
        for (String beanName : beanNames) {
            try {
               result.put(beanName, getBean(beanName, type));
-> the bean is created even if its not the qualified one
            }
    ...........
            }
        }

我可以在创建所有bean condidates之前修改Spring代码以找到合格的Bean,但我想知道是否还有其他方法可以做?

2 个答案:

答案 0 :(得分:1)

该改进已被接受并在4.1.9和4.2.4版本中推出 有关详细信息,请参阅错误报告:https://jira.spring.io/browse/SPR-13741

答案 1 :(得分:-1)

context.xml中有一个懒惰的bean实例化:

lazy-init="true" 

http://www.javabeat.net/how-to-lazy-initialize-spring-beans/