1. 程式人生 > 實用技巧 >Spring原始碼入門——XmlBeanFactory原始碼學習

Spring原始碼入門——XmlBeanFactory原始碼學習

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

1         XmlBeanFactory factory = new XmlBeanFactory( new ClassPathResource("knights.xml"));
2         //替換為
3         DefaultListableBeanFactory fac = new DefaultListableBeanFactory();
4         BeanDefinitionReader reader = new XmlBeanDefinitionReader(fac);
5 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中寫到了這麼一段話:

  XmlBeanFactorywas deprecated because it existed before theApplicationContext

abstraction did, and theApplicationContexthierarchy was specifically designed to accommodate concrete types aligned with different bean definition types (GenericXmlApplicationContext,AnnotationConfigApplicationContext, etc), while theBeanFactoryhierarchy represents a more fundamental abstraction not designed for such variability.XmlBeanFactoryis the one historical exception to that rule, and the deprecation reflects that fact. Given thatGenericXmlApplicationContextprovides equal if not greater convenience (given the String-andResource-based constructors), undeprecating is unlikely at this point.

  先從XmlBeanFactory的繼承體系開始(不完整):  概念上來講,

  •   BeanFactory,定義獲取bean及bean的各種屬性
  •   BeanDefinitionRegistry,定義對BeanDefinition的各種增刪改查操作。
  •   BeanDefinitionReader,定義從資原始檔載入為BeanDefinition的流程

  這樣我們可以把XmlBeanFactory載入bean的操作分為兩個部分,1,讀取檔案解析為BeanDefinition集合註冊給registry(參考:http://www.cnblogs.com/jason0529/p/5239139.html);2,讀取BeanDefinition並轉換為bean例項返回。第一個流程就是BeaDefinitionReader這個介面定義完成的事情,第二步是BeanFactory需要完成的工作。