簡單解析Spring核心IOC容器原理

來源:互聯網
上載者:User

標籤:actor   cat   ons   exce   classpath   map   ebe   context   核心   

將大體流程解析了一邊,具體可以看原始碼一個方法一個方法的跟下

XmlBeanFactory的功能是建立在DefaultListableBeanFactory這個基本容器的基礎上的,並在這個基本容器的基礎上實行了其他諸如XML讀取的附加功能。

DefaultListableBeanFactory是BeanFactory的一個預設實作類別。

public class XmlBeanFactory extends DefaultListableBeanFactory {    private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);        /**     * Resource是Spring中對與外部資源的抽象,最常見的是對檔案的抽象,特別是XML檔案。     * 而且Resource裡面通常儲存了Spring使用者的Bean定義     * 比如applicationContext.xml在被載入時,就會被抽象為Resource來處理。     */    public XmlBeanFactory(Resource resource) throws BeansException {        this(resource, null);    }        public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {        super(parentBeanFactory);        this.reader.loadBeanDefinitions(resource);    }}

簡單樣本:

public class MySimpleBeanFactory {    public static void main(String[] args) {        ClassPathResource resource = new ClassPathResource("META-INF/beans.xml");        BeanFactory beanFactory = new XmlBeanFactory(resource);        User user = beanFactory.getBean("user1", User.class);        System.out.println(user.getName()+" : "+user.getAge());    }}

建立容器的步驟:

  1. 建立bean設定檔的抽象Resource
  2. 建立BeanFactory,例如:XmlBeanFactory
  3. 解析Bean,建立一個BeanDefinition讀取器,例如:XmlBeanDefinitionReader->DefaultBeanDefinitionDocumentReader->BeanDefinitionParserDelegate
  4. 得到BeanDefinition後註冊到DefaultListableBeanFactory中:
// 最後BeanDefinition就是放到這個map裡的Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>(256);

以後會慢慢完善。

簡單解析Spring核心IOC容器原理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.