• Jxin
    2020-01-23
    1.基本都是单一查找,依赖查找可以在LB这种场景应用,但这个分层查找有啥用?
    2.看着demo随手改了下,相对于双亲模式,多了一个HierarchicalBeanFactory的类型判断。

        private static boolean containsBean(HierarchicalBeanFactory beanFactory, String beanName) {
            final BeanFactory parentBeanFactory = beanFactory.getParentBeanFactory();
            // parentBeanFactory 非层级结构 则看自己
            if (!(parentBeanFactory instanceof HierarchicalBeanFactory)) {
                return beanFactory.containsLocalBean(beanName);
            }
            // parentBeanFactory 是层级结构 先看parentBeanFactory
            if (containsBean((HierarchicalBeanFactory) parentBeanFactory, beanName)) {
                return true;
            }
            // parentBeanFactory 是层级结构 且parentBeanFactory不包含, 则看自己
            return beanFactory.containsLocalBean(beanName);
        }
    展开

    作者回复: 1.基本都是单一查找,依赖查找可以在LB这种场景应用,但这个分层查找有啥用?

    比如 Spring MVC 中,Biz 组件放在 Root ApplicationContext,而 Web 组件放在 DispatcherServlet 的 ApplicationContext,后者是前者的子 ApplicationContext,所以,子 ApplicationContext 可以读取父 ApplicationContext

    
     2
  • will
    2020-02-04
    如果父子BeanFactory里存在相同名称的Bean,BeanFactoryUtils#beansOfTypeIncludingAncestors 方法好像是排除父亲BeanFactory里的Bean,返回子BeanFactory里的Bean吧

    作者回复: 是的,会派出,这个和 ClassLoader 类似

    
    
  • 勤劳的明酱
    2020-01-29
    根据BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory lbf, Class<T> type)
    方法的描述
    such beans will be returned from the lowest factory that they are being found in,
    hiding corresponding beans in ancestor factories.</b> This feature allows for
    'replacing' beans by explicitly choosing the same bean name in a child factory;
    the bean in the ancestor factory won't be visible then, not even for by-type lookups.
    这里的意思应该是会选择子factory里的bean,而不是选择parentFactory里面的bean来解决冲突,在这个类里面不是类似双亲委派的选择方式,它们的设计初衷不一致
    展开

    作者回复: BeanFactory 的双亲委派和 ClassLoader 类似,和 Bean 冲突没有直接关系。 BeanFactoryUtils#beansOfTypeIncludingAncestors 仍旧是递归地查找指定类型的 Bean 集合,并且是在所有层次类查找,只不过该方法会排除子 BeanFactory 已存在的 Bean,这是一种就近原则的设计。

     3
    
我们在线,来聊聊吧