天天看點

Spring源碼入門——XmlBeanFactory源碼學習

XmlBeanFactory雖然在Spring 3.1之後标記為@Deprecated,具體用法改為

XmlBeanFactory factory = new XmlBeanFactory( new ClassPathResource("knights.xml"));
        //替換為
        DefaultListableBeanFactory fac = new DefaultListableBeanFactory();
        BeanDefinitionReader reader = new XmlBeanDefinitionReader(fac);
        reader.loadBeanDefinitions( new ClassPathResource("knights.xml"));
           

而我們通過XmlBeanFactory的執行個體化方式可以看到新的寫法隻是把原來的執行個體化流程拿出來了而已。而Spring的Jira中寫到了這麼一段

private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);

    public XmlBeanFactory(Resource resource) throws BeansException {
        this(resource, null);
    }

    
    public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
        super(parentBeanFactory);
        this.reader.loadBeanDefinitions(resource);
    }
           

而Spring的Jira中寫到了這麼一段話:

  XmlBeanFactory was deprecated because it existed before the ApplicationContext abstraction did, and theApplicationContext hierarchy was specifically designed to accommodate concrete types aligned with different bean definition types (GenericXmlApplicationContext, AnnotationConfigApplicationContext, etc), while the BeanFactory hierarchy represents a more fundamental abstraction not designed for such variability. XmlBeanFactory is the one historical exception to that rule, and the deprecation reflects that fact. Given that GenericXmlApplicationContext provides equal if not greater convenience (given the String- and Resource-based constructors), undeprecating is unlikely at this point.

  先從XmlBeanFactory的繼承體系開始(不完整):

Spring源碼入門——XmlBeanFactory源碼學習

  概念上來講,

  •   BeanFactory,定義擷取bean及bean的各種屬性
  •   BeanDefinitionRegistry,定義對BeanDefinition的各種增删改查操作。
  •   BeanDefinitionReader,定義從資源檔案加載為BeanDefinition的流程

  這樣我們可以把XmlBeanFactory加載bean的操作分為兩個部分

1,讀取檔案解析為BeanDefinition集合注冊給registry

2,讀取BeanDefinition并轉換為bean執行個體傳回。第一個流程就是BeaDefinitionReader這個接口定義完成的事情,第二步是BeanFactory需要完成的工作。