Spring IOC執行流程簡單解析

IOC的基本使用

廢話不多說,我這裏直接貼代碼了:

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="studentService" class="com.jay.service.impl.StudentServiceImpl">
        <constructor-arg name="id" value="1"></constructor-arg>
        <property name="name" value="jay"></property>
    </bean>


</beans>

StudentService:

package com.jay.service;

public interface StudentService {
    void study();
}

StudentServiceImpl: 這裏我加了兩個屬性,並且實現了一個BeanFactoryPostProcessor,在工廠類創建成功後會執行postProcessBeanFactory方法

package com.jay.service.impl;

import com.jay.service.StudentService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class StudentServiceImpl implements StudentService, BeanFactoryPostProcessor {

    int id;

    String name;

    public StudentServiceImpl(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void study() {
        System.out.println("好好學習");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("hello factory");
    }
}

main:

package com.jay.test;


import com.jay.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class StudentTest {
    public static void main(String[] args){
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        StudentService studentService=(StudentService)applicationContext.getBean("studentService");
        studentService.study();
    }

}

BeanFactory

BeanFactory就是創建Bean的工廠類,它是一個接口,而我們熟悉的ApplicationContext接口就是這個接口的子接口,看結構圖吧~:

在這裏插入圖片描述

可以看到,ApplicationContext繼承了好多個接口,但在這裏主要討論ListableBeanFactory,它纔是爸爸!

初始化ApplicationContext

第一步,肯定是從ClassPathXmlApplicationContext的構造方法開始,這個創建ApplicationContext的過程其實就是創建BeanFactory的過程。

public ClassPathXmlApplicationContext(
      String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
      throws BeansException {

   super(parent);
   //這一步其實是處理配置文件的命名格式
   setConfigLocations(configLocations);
   if (refresh) {
      //這是核心方法,在refresh裏完成BeanFactory的創建
      refresh();
   }
}

那就看一下refresh方法(爲啥取名叫refresh,而不是init啥的?這是因爲我們可以調用這個方法對BeanFactory進行重建)

refresh方法

@Override
public void refresh() throws BeansException, IllegalStateException {
   //加鎖,否則在refresh執行過程中,又有其他線程跑來重建怎麼辦?
   synchronized (this.startupShutdownMonitor) {
      // 這一步很簡單,就是記錄下容器的啓動時間,將狀態切換爲轉換狀態什麼的。
      prepareRefresh();

      // 這是關鍵步驟,它會將配置文件中的<bean>標籤解析爲BeanDefinition對象,然後註冊到BeanFactory中
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      
      prepareBeanFactory(beanFactory);

      try {
         //還記得之前的實現類裏面實現了BeanFactoryPostProcessor接口,會在工廠類創建完成後調用postProcessBeanFactory方法嗎?沒錯,這裏就是即將要進行後處理
         postProcessBeanFactory(beanFactory);

         // 真正地執行後處理
         invokeBeanFactoryPostProcessors(beanFactory);

         //註冊BeanPostProcessor的實現類,裏面有兩個方法,分別是Bean前處理器和Bean後處理
         registerBeanPostProcessors(beanFactory);

         // Initialize message source for this context.
         initMessageSource();

         // Initialize event multicaster for this context.
         initApplicationEventMulticaster();

         // Initialize other special beans in specific context subclasses.
         onRefresh();

         // Check for listener beans and register them.
         registerListeners();

         //這是重點!前面只是將bean標籤進行解析和註冊,這裏纔是真正地創建實例的地方
         finishBeanFactoryInitialization(beanFactory);

         // Last step: publish corresponding event.
         finishRefresh();
      }

      catch (BeansException ex) {
         if (logger.isWarnEnabled()) {
            logger.warn("Exception encountered during context initialization - " +
                  "cancelling refresh attempt: " + ex);
         }

         // Destroy already created singletons to avoid dangling resources.
         destroyBeans();

         // Reset 'active' flag.
         cancelRefresh(ex);

         // Propagate exception to caller.
         throw ex;
      }

      finally {
         // Reset common introspection caches in Spring's core, since we
         // might not ever need metadata for singleton beans anymore...
         resetCommonCaches();
      }
   }
}

obtainFreshBeanFactory方法

這個是全文中最重要的幾個方法之一,做了這些事:初始化BeanFactory,加載bean標籤,將bean註冊到BeanFactory中:

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
   refreshBeanFactory();
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
   if (logger.isDebugEnabled()) {
      logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
   }
   return beanFactory;
}

首先是調用了refreshBeanFactory():

protected final void refreshBeanFactory() throws BeansException {
    //當前的ApplicationContext是否已經包含了BeanFactory,若有則進行銷燬
   if (hasBeanFactory()) {
      destroyBeans();
      closeBeanFactory();
   }
   try {
       //初始化一個ListableBeanFactory對象。噢!所以說這個BeanFactory表面上是ApplicationContext,實際上是 DefaultListableBeanFactory
      DefaultListableBeanFactory beanFactory = createBeanFactory();
       //設置BeanFactory的兩個屬性,即是否允許覆蓋和循環依賴
      beanFactory.setSerializationId(getId());
      customizeBeanFactory(beanFactory);
      //將bean加載到beanFactory中
      loadBeanDefinitions(beanFactory);
      synchronized (this.beanFactoryMonitor) {
         this.beanFactory = beanFactory;
      }
   }
   catch (IOException ex) {
      throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
   }
}

createBeanFactory方法

protected DefaultListableBeanFactory createBeanFactory() {
   return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}

這個方法很簡單,就是直接new了一個DefaultListableBeanFactory對象而已

customizeBeanFactory方法

protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
   if (this.allowBeanDefinitionOverriding != null) {
      beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
   }
   if (this.allowCircularReferences != null) {
      beanFactory.setAllowCircularReferences(this.allowCircularReferences);
   }
}

也很簡單,就是set了一下

loadBeanDefinitions方法

這個方法就是很重要的了,這個方法根據配置文件對各個bean進行加載,然後註冊到BeanFactory中:

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
   //創建一個XmlBeanDefinitionReader對象
   XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

   // Configure the bean definition reader with this context's
   // resource loading environment.
   beanDefinitionReader.setEnvironment(this.getEnvironment());
   beanDefinitionReader.setResourceLoader(this);
   beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

   // Allow a subclass to provide custom initialization of the reader,
   // then proceed with actually loading the bean definitions.
   initBeanDefinitionReader(beanDefinitionReader);
    //調用了一個重載方法
   loadBeanDefinitions(beanDefinitionReader);
}

這個重載loadBeanDefinitions方法其實就是對XML文件一頓解析,得到一棵DOM樹,然後解析結果作爲參數,調用:

 doRegisterBeanDefinitions(root);
protected void doRegisterBeanDefinitions(Element root) {
   // Any nested <beans> elements will cause recursion in this method. In
   // order to propagate and preserve <beans> default-* attributes correctly,
   // keep track of the current (parent) delegate, which may be null. Create
   // the new (child) delegate with a reference to the parent for fallback purposes,
   // then ultimately reset this.delegate back to its original (parent) reference.
   // this behavior emulates a stack of delegates without actually necessitating one.
   BeanDefinitionParserDelegate parent = this.delegate;
   this.delegate = createDelegate(getReaderContext(), root, parent);

   if (this.delegate.isDefaultNamespace(root)) {
      String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
      if (StringUtils.hasText(profileSpec)) {
         String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
               profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
         if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
            if (logger.isInfoEnabled()) {
               logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
                     "] not matching: " + getReaderContext().getResource());
            }
            return;
         }
      }
   }

   preProcessXml(root);
    //主要看這,這是真正對標籤進行轉化的
   parseBeanDefinitions(root, this.delegate);
   postProcessXml(root);

   this.delegate = parent;
}
parseBeanDefinitions(root, this.delegate)方法
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
   //如果是<import />、<alias />、<bean /> 和 <beans />標籤,走這裏
   if (delegate.isDefaultNamespace(root)) {
      NodeList nl = root.getChildNodes();
      for (int i = 0; i < nl.getLength(); i++) {
         Node node = nl.item(i);
         if (node instanceof Element) {
            Element ele = (Element) node;
            if (delegate.isDefaultNamespace(ele)) {
               parseDefaultElement(ele, delegate);
            }
            else {
               delegate.parseCustomElement(ele);
            }
         }
      }
   }
    //其他標籤走這裏
   else {
      delegate.parseCustomElement(root);
   }
}

反正接下來就是將解析到的標籤轉化爲BeanDefinition對象,然後將對象註冊到ApplicationContext的Map中,就不詳細說了,等有時間再寫一個相關的解析(逃)

弄完之後,bean的解析完成了,也已經註冊到BeanFactory(也就是ApplicationContext中的beanFactory屬性,也就是DefaultListableBeanFactory對象)中了,那接下來就是對bean進行實例化了,這下又回到refresh方法中了,再貼一下:

@Override
public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      // Prepare this context for refreshing.
      prepareRefresh();

      // Tell the subclass to refresh the internal bean factory.
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // Prepare the bean factory for use in this context.
      prepareBeanFactory(beanFactory);

      try {
         // Allows post-processing of the bean factory in context subclasses.
         postProcessBeanFactory(beanFactory);

         // Invoke factory processors registered as beans in the context.
         invokeBeanFactoryPostProcessors(beanFactory);

         // Register bean processors that intercept bean creation.
         registerBeanPostProcessors(beanFactory);

         // Initialize message source for this context.
         initMessageSource();

         // Initialize event multicaster for this context.
         initApplicationEventMulticaster();

         // Initialize other special beans in specific context subclasses.
         onRefresh();

         // Check for listener beans and register them.
         registerListeners();

         // Instantiate all remaining (non-lazy-init) singletons.
         finishBeanFactoryInitialization(beanFactory);

         // Last step: publish corresponding event.
         finishRefresh();
      }

      catch (BeansException ex) {
         if (logger.isWarnEnabled()) {
            logger.warn("Exception encountered during context initialization - " +
                  "cancelling refresh attempt: " + ex);
         }

         // Destroy already created singletons to avoid dangling resources.
         destroyBeans();

         // Reset 'active' flag.
         cancelRefresh(ex);

         // Propagate exception to caller.
         throw ex;
      }

      finally {
         // Reset common introspection caches in Spring's core, since we
         // might not ever need metadata for singleton beans anymore...
         resetCommonCaches();
      }
   }
}

finishBeanFactoryInitialization方法

refresh下一個要講的方法就是finishBeanFactoryInitialization(beanFactory)了,這一步會初始化所有除了設置了懶加載的所有bean。初始化過程就是,如果沒有使用動態代理,那麼會使用反射來創建,如果使用了動態代理,那麼久創建對應的Proxy代理類,實例化之後的bean會存進ApplicationContex裏的beanFactory中,通過一個ConcurrentHashMap進行存儲。

那這一步做完,整個ApplicationContext就算是初始化完成了,康一康整個ApplicationContext長什麼樣:

在這裏插入圖片描述

beanFactory下面還有:

在這裏插入圖片描述

可以看到,ApplicationContext實際上是ClassPathXmlApplicationContext對象,而其中有一個beanFactory屬性,爲DefaultListableBeanFactory對象,這個對象裏,有一個ConcurrentHashMap,裏面的key值爲bean的名字,value爲對應的實例對象。而後面的getBean()方法實際上就是從這裏取的。

獲取bean對象

getBean方法

也就是調用ClassPathXmlApplicationContext的getBean方法():

這是AbstractApplicationContext類中的方法,看一下結構圖:

在這裏插入圖片描述

可以看到,ClassPathXmlApplicationContext是AbstractApplicationContext的子類,那直接看這個方法吧:

public Object getBean(String name) throws BeansException {
    //這一步啥也沒做==
   assertBeanFactoryActive();
   return getBeanFactory().getBean(name);
}

getBeanFactory方法

public final ConfigurableListableBeanFactory getBeanFactory() {
   synchronized (this.beanFactoryMonitor) {
      if (this.beanFactory == null) {
         throw new IllegalStateException("BeanFactory not initialized or already closed - " +
               "call 'refresh' before accessing beans via the ApplicationContext");
      }
       //返回了this.beanFactory,不就是DefaultListableBeanFactory實例麼?
      return this.beanFactory;
   }
}

在這裏插入圖片描述

從這裏也可以看出來

getBean方法

public Object getBean(String name) throws BeansException {
   return doGetBean(name, null, null, false);
}

調用了doGetBean

doGetBean方法

protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
      @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

   final String beanName = transformedBeanName(name);
   Object bean;

   // 調用了這個方法
   Object sharedInstance = getSingleton(beanName);
   .....
}

調用了getSingleton,進去看看

getSingleton方法

最終會到這裏

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    //主要是這裏!
   Object singletonObject = this.singletonObjects.get(beanName);
   if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
      synchronized (this.singletonObjects) {
         singletonObject = this.earlySingletonObjects.get(beanName);
         if (singletonObject == null && allowEarlyReference) {
            ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
            if (singletonFactory != null) {
               singletonObject = singletonFactory.getObject();
               this.earlySingletonObjects.put(beanName, singletonObject);
               this.singletonFactories.remove(beanName);
            }
         }
      }
   }
   return singletonObject;
}

看看this.singletonObjects是什麼:

在這裏插入圖片描述

害!可不就是DefaultListableBeanFactory中這個ConcurrentHashMap嘛,至此就拿到實例了

那執行流程粗略就是這樣了,有一些細節上的操作沒有仔細看,但是總體方向還是清楚的

那此時面試官問,Spring IOC的執行流程是啥呀?

A:執行的第一件事,就是要加載ApplicationContext對象,這個ApplicationContext是一個接口,並且是BeanFactory的子接口,BeanFactory就是存放與bean相關數據的一個容器,所以說初始化ApplicationContext就是初始化BeanFactory,與Bean相關的操作都是基於ApplicationContext來執行的,或者準確來說並不是由ApplicationContext親自執行的,它內部還有一個beanFactory屬性,這個beanFactory最終會被賦值爲一個DefaultListableBeanFactory對象,那其實所有的bean操作都是基於這個屬性完成的。

在創建好BeanFactory後,之後就要會對配置文件進行解析,每一個bean標籤都會解析成一個BeanDefinition對象,然後註冊到BeanFactory中,註冊的方式是基於一個ConcurrentHashMap,key值爲bean標籤的名,value就是這個BeanDefinition對象。

註冊完了之後,接下來就是對bean進行實例化了,實例化的過程分兩種情況,如果對應的類使用了動態代理,那麼就要實例化它對應的Proxy代理類,若沒有使用動態代理,則通過反射進行創建。創建好的實例同樣是註冊在beanFactory中的一個ConcurrentHashMap中。至此ApplicationContext的創建就算是完成了。

後續調用getBean方法,其實就是從ApplicationContext的beanFactory屬性中的ConcurrentHashMap進行獲取。

這就是IOC執行的一個流程。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章