深入淺出解讀 Spring 原始碼:IOC/AOP 篇

GitChat的部落格發表於2018-04-12

還在機械地打程式碼?只知道如何使用,卻不知道做了什麼,那麼你註定只能是一個碼農。Spring 框架幾乎整合一半 Javaweb 開發的江山,但是你只知道如何寫,不知道為什麼要這麼寫,也不知道要如何優化。

本場 Chat 將讓大家瞭解 Spring 的執行原理、深度解析 IOC 和 AOP、最後你還可以自己寫一個小型 Spring 框架!

實錄提要:

  • 閱讀原始碼的正確姿勢/最佳實踐是什麼?
  • Spring 原始碼哪本書比較好?
  • 設計模式應該主要掌握哪幾種?
  • 如何進行統一加解密使用 Spring(還要考慮到上傳檔案返回檔案資料的請款)?
  • 模組化思想是什麼?
  • Spring 原始碼那麼多的類,類之間呼叫比較複雜,從哪裡開始看比較好?

目錄

  • 一、說說我自己
  • 二、IOC入門篇之概念理解
  • 三、深入理解IOC核心類
  • 四、IOC體系結構原始碼剖析

說說我自己

我給大家介紹一下我的學習方法。學習的三種階段:入門、掌握、精通。

  • 入門篇 -- 讀文章 對這個知識有一定的瞭解,瞭解大概的發展趨勢以及使用複雜程度,達到基本可以使用程度。
  • 掌握篇 -- 看網上的教程 對這個知識使用並瞭解一些出現bug解決方案,擴充套件使用途徑。
  • 精通篇 -- 對知識體系結構已有完整認知 需要讀別人寫的書 加上自己親自打程式碼時間 完全瞭解這個知識發展淵源。

我也是和大家一樣,大三來北京在一個小公司實習,我還是一個專科生 ,我並不是什麼大神,只是在spring方面花費比大家多一些時間而已。

送給所有有夢想的我們一句話 :相信自己,力量在心中!!

IOC入門篇之概念理解

控制反轉(IoC):概念的描述:

Martin Fowler提出,那些方面的控制被反轉了? - 他給出的結論:依賴物件的獲取被反轉了,基於這個結論他為控制反轉創造了一個由兩個或多各類批次之間的合作來實現業務邏輯的,這是的每一個物件都需要與其合作的物件(也就是他依賴的物件)的引用。如果這個獲取過程要考自身實現,那麼如果如你所見,這將導致程式碼高度耦合難以測試。--《摘自維基百科》

我是這樣理解IOC容器:以水桶為例,有大的,小的,有金的,銀的,各種各樣。IOC容器也如此,每種不同的容器有自己功能,但是他們有一個是不能改變的,那就是裝水,我們所學習的IOC容器也一樣。

IOC是Inversion of Control的縮寫,由於引進了中間位置的第三方,也就是IOC容器使得沒有關聯關係的類有了一個共同的關係--被ICO容器所管理,所以說IOC容器起到了粘合劑的作用。

DI是Dependency Injection的所寫,是指通過引入IOC容器,利用類與類相關的依賴關係,注入的方式,實現程式碼重用以及物件之間的解耦合。(說到解耦合,三大框架都是為了解耦合,面試時候千萬別說解耦合 ,說具體,哈哈。)

IOC的好處,初始化的過程中就不可避免的會寫大量的new,只需要維護XML或註解,不需要大量的修改程式碼,IOC容器是分層的,從最底層BeanFactory網上找(後面原始碼解讀會詳細講解),實現類與類之間的解耦合,可以將程式碼分離,每個人只需要寫自己的部分,利於團隊協作。

複合IOC規範的產品: Spring、Guice、Pico Container、Avalon、HiveMind;重量級的有EJB,JBoss,Jdon等等。以上除了Spring別的都沒用過,出去面試吹一下也沒啥^-^

使用IOC容器的小缺點: 引入第三方工具,對效能,初始化等速度均有影響,需要配置一大堆(springboot簡化了好多,推薦大家從基於xml的spring學起),通過反射機制建立物件,效率較低~~~實際沒影響。

深入理解IOC核心類

BeanFactory的基本類體系結構:

BeanFactory的基本類體系結構

如圖所示:BeanFactory是最基礎的IOC底層,定義了一些bean的基本屬性,XMLBeanFactory算比較高階的IOC容器了,IOC容器是分層的,每一層都有自己需要做的功能,一下將簡略展示IOC各個容器的功能。

  • BeanFactory 負責 獲取bean,封裝判斷bean容器是否包含bean,判斷bean是否為單利/指定型別,獲取類的別名,型別匹配等。

  • ListanleBeanFactory 繼承自BeanFactory 封裝bean的一些基本屬性資訊,如類的個數,型別,別名等,可以根據條件獲取指定bean。

  • AutowireCapableBeanFactory 繼承自BeanFactory 封裝提供一系列自動裝噢誒bean的策略,自動注入初始化以及bean的前/後處理器,分解依賴等。

  • HierarchicalBeanFactory 繼承自BeanFactory 封裝兩個方法,一個獲取bean工廠的父工廠,另一個判斷本地工廠是否包含指定bean。

  • SinglentonRegistry 定義對單例註冊及獲取是否包含等判斷。

  • ConfigurableBeanFactory 提供配置Factory的方法。

  • AliaRegistry 提供對bean的別名的增刪改查操作。

  • BeanDefinitionRegister 使用BeanDefinition修飾bean,提供對BeanDefinition的增刪改操作。

  • ConfigurableBeanFactory 提供配置bean的方法 。

  • ConfigurableListableBeanFactory 配置清單BeanFactory指定忽略型別,介面等。

  • AbstractAutowireCapableBeanFactory 綜合AbstractBeanFactory,對接自動裝配bean。

  • DefaultListableBeanFactory 綜合上面的功能,主要針對bean的註冊。

IOC體系結構原始碼剖析

XmlBeanFactory 實現類體系結構:

XmlBeanFactory 實現類體系結構

Spring 5.x 原始碼下載

你也可以到github上下載gradle構架的Spring 然後把你的eclipse配置gradle 安裝外掛專案。

SimpleAliasRegistry

public class SimpleAliasRegistry implements AliasRegistry {// 包含別名的map 就我瞭解 所有包含併發操作的都是用currentHashMap 推薦大家也使用private final Map<String, String> aliasMap = new ConcurrentHashMap<String, String>(16);@Overridepublic void registerAlias(String name, String alias) {    Assert.hasText(name, "'name' must not be empty");    Assert.hasText(alias, "'alias' must not be empty");    // 若別名和實際bean名字相同,移除別名    if (alias.equals(name)) {        this.aliasMap.remove(alias);    }    else {        // 獲取bean的真實名        String registeredName = this.aliasMap.get(alias);        if (registeredName != null) {            if (registeredName.equals(name)) {                // An existing alias - no need to re-register                return;            }            if (!allowAliasOverriding()) {                throw new IllegalStateException("Cannot register alias '" + alias + "' for name '" +                        name + "': It is already registered for name '" + registeredName + "'.");            }        }        checkForAliasCircle(name, alias);// 當bean名字與name相同 檢查別名是否相同 相同丟擲異常 已存在的別名        this.aliasMap.put(alias, name);     }}// SO WHAT ?    protected boolean allowAliasOverriding() {    return true;}// checkForAliasCircle呼叫的 上文指出public boolean hasAlias(String name, String alias) {    for (Map.Entry<String, String> entry : this.aliasMap.entrySet()) {        String registeredName = entry.getValue();        if (registeredName.equals(name)) {            String registeredAlias = entry.getKey();            return (registeredAlias.equals(alias) || hasAlias(registeredAlias, alias));        }    }    return false;}// 移除別名@Overridepublic void removeAlias(String alias) {    String name = this.aliasMap.remove(alias);    if (name == null) {        throw new IllegalStateException("No alias '" + alias + "' registered");    }}// 是否是別名@Overridepublic boolean isAlias(String name) {    return this.aliasMap.containsKey(name);}// 獲取所有別名@Overridepublic String[] getAliases(String name) {    List<String> result = new ArrayList<String>();    synchronized (this.aliasMap) {        retrieveAliases(name, result);    }    return StringUtils.toStringArray(result);}// 找出所有name對應的別名 存入List<String>private void retrieveAliases(String name, List<String> result) {    for (Map.Entry<String, String> entry : this.aliasMap.entrySet()) {        String registeredName = entry.getValue();        if (registeredName.equals(name)) {            String alias = entry.getKey();            result.add(alias);            retrieveAliases(alias, result);        }    }}// 處理所有的別名,如果處理正確,把原來的用解析後的替換public void resolveAliases(StringValueResolver valueResolver) {    Assert.notNull(valueResolver, "StringValueResolver must not be null");    synchronized (this.aliasMap) {        Map<String, String> aliasCopy = new HashMap<String, String>(this.aliasMap);        for (String alias : aliasCopy.keySet()) {            String registeredName = aliasCopy.get(alias);            String resolvedAlias = valueResolver.resolveStringValue(alias);            String resolvedName = valueResolver.resolveStringValue(registeredName);            if (resolvedAlias == null || resolvedName == null || resolvedAlias.equals(resolvedName)) {                this.aliasMap.remove(alias);            }            else if (!resolvedAlias.equals(alias)) {                String existingName = this.aliasMap.get(resolvedAlias);                if (existingName != null) {                    if (existingName.equals(resolvedName)) {                        // Pointing to existing alias - just remove placeholder                        this.aliasMap.remove(alias);                        break;                    }                    throw new IllegalStateException(                            "Cannot register resolved alias '" + resolvedAlias + "' (original: '" + alias +                            "') for name '" + resolvedName + "': It is already registered for name '" +                            registeredName + "'.");                }                checkForAliasCircle(resolvedName, resolvedAlias);                this.aliasMap.remove(alias);                this.aliasMap.put(resolvedAlias, resolvedName);            }            else if (!registeredName.equals(resolvedName)) {                this.aliasMap.put(alias, resolvedName);            }        }    }}// 若當前map中存在別名和name相同 拋異常protected void checkForAliasCircle(String name, String alias) {    if (hasAlias(alias, name)) {        throw new IllegalStateException("Cannot register alias '" + alias +                "' for name '" + name + "': Circular reference - '" +                name + "' is a direct or indirect alias for '" + alias + "' already");    }}//根據name這個Key,在aliasMap中不斷迴圈的取對應的value,如果取得到,就繼續根據這個value取值,不斷迴圈繼續。直到取不到,就把這個在aliasMap中無對應值的key返回。public String canonicalName(String name) {    String canonicalName = name;    // Handle aliasing...    String resolvedName;    do {        resolvedName = this.aliasMap.get(canonicalName);        if (resolvedName != null) {            canonicalName = resolvedName;        }    }    while (resolvedName != null);    return canonicalName;    }}

DefaultSingletonBeanRegistry

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {    // 看看人家 程式碼寫的多規範 我要學習    protected static final Object NULL_OBJECT = new Object();    // 定義記錄log日誌    protected final Log logger = LogFactory.getLog(getClass());    // 單例bean快取    private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);    // 單例工廠快取    private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);    // 沒註冊之前存放單例記錄    private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);    // 註冊過的單例    private final Set<String> registeredSingletons = new LinkedHashSet<String>(256);    // 使用ConcurrentHashMap<T,Boolean> -- set<T> 底層我看過 那個Boolean屬性true 包含    // 這樣的Set集合是採用鎖分段的機制 對高併發操作優化    // 即將建立的單例類    private final Set<String> singletonsCurrentlyInCreation =            Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));    // 正在建立的單例類    private final Set<String> inCreationCheckExclusions =            Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));    // 異常集合    private Set<Exception> suppressedExceptions;    // 單例類是否真正被銷燬    private boolean singletonsCurrentlyInDestruction = false;    // disposable介面的例項    private final Map<String, Object> disposableBeans = new LinkedHashMap<String, Object>();    // bean名稱和bean所有包含的Bean的名稱的map    private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<String, Set<String>>(16);    // bean名稱和所有依賴於Bean的名稱的map    private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<String, Set<String>>(64);    // bean名稱和bean所依賴的所有名稱的map    private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<String, Set<String>>(64);    // 註冊單例類 重複註冊拋異常    @Override    public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {        Assert.notNull(beanName, "'beanName' must not be null");        synchronized (this.singletonObjects) {            Object oldObject = this.singletonObjects.get(beanName);            if (oldObject != null) {                throw new IllegalStateException("Could not register object [" + singletonObject +                        "] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");            }            addSingleton(beanName, singletonObject);        }    }    // 從earlySingletonObjects,singletonFactories移除    // 註冊bean以及將bean新增到earlySingletonObjects    protected void addSingleton(String beanName, Object singletonObject) {        synchronized (this.singletonObjects) {            this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));            this.singletonFactories.remove(beanName);//             this.earlySingletonObjects.remove(beanName);            this.registeredSingletons.add(beanName);        }    }    // 註冊一個單例工廠類,註冊後從earlySingletonObjects移除    protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {        Assert.notNull(singletonFactory, "Singleton factory must not be null");        synchronized (this.singletonObjects) {            if (!this.singletonObjects.containsKey(beanName)) {                this.singletonFactories.put(beanName, singletonFactory);                this.earlySingletonObjects.remove(beanName);                this.registeredSingletons.add(beanName);            }        }    }    @Override    public Object getSingleton(String beanName) {        return getSingleton(beanName, true);    }    // 獲取單例類    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 != NULL_OBJECT ? singletonObject : null);    }    // 獲取指定的單例Bean    public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {        Assert.notNull(beanName, "'beanName' must not be null");        synchronized (this.singletonObjects) {            Object singletonObject = this.singletonObjects.get(beanName);            // 如果從當前的單例快取中沒找到指定bean            if (singletonObject == null) {                if (this.singletonsCurrentlyInDestruction) {//當前單例正在摧毀                    throw new BeanCreationNotAllowedException(beanName,                            "Singleton bean creation not allowed while singletons of this factory are in destruction " +                            "(Do not request a bean from a BeanFactory in a destroy method implementation!)");                }                if (logger.isDebugEnabled()) {                    logger.debug("Creating shared instance of singleton bean '" + beanName + "'");                }                beforeSingletonCreation(beanName);// 單例類建立之前執行                boolean newSingleton = false;                boolean recordSuppressedExceptions = (this.suppressedExceptions == null);                if (recordSuppressedExceptions) {                    this.suppressedExceptions = new LinkedHashSet<Exception>();                }                try {                    singletonObject = singletonFactory.getObject();                    newSingleton = true;                }                catch (IllegalStateException ex) {                    // Has the singleton object implicitly appeared in the meantime ->                    // if yes, proceed with it since the exception indicates that state.                    singletonObject = this.singletonObjects.get(beanName);                    if (singletonObject == null) {                        throw ex;                    }                }                catch (BeanCreationException ex) {                    if (recordSuppressedExceptions) {                        for (Exception suppressedException : this.suppressedExceptions) {                            ex.addRelatedCause(suppressedException);                        }                    }                    throw ex;                }                finally {                    if (recordSuppressedExceptions) {                        this.suppressedExceptions = null;                    }                    afterSingletonCreation(beanName);                }                if (newSingleton) {                    addSingleton(beanName, singletonObject);                }            }            return (singletonObject != NULL_OBJECT ? singletonObject : null);        }    }    // 新增異常    protected void onSuppressedException(Exception ex) {        synchronized (this.singletonObjects) {            if (this.suppressedExceptions != null) {                this.suppressedExceptions.add(ex);            }        }    }    // 根據名稱移除本容器中快取的對應的單例Bean以及所有關聯移除    protected void removeSingleton(String beanName) {        synchronized (this.singletonObjects) {            this.singletonObjects.remove(beanName);            this.singletonFactories.remove(beanName);            this.earlySingletonObjects.remove(beanName);            this.registeredSingletons.remove(beanName);        }    }    // 判斷容器是否包含單例bean    @Override    public boolean containsSingleton(String beanName) {        return this.singletonObjects.containsKey(beanName);    }    // 獲取所有單例類名字    @Override    public String[] getSingletonNames() {        synchronized (this.singletonObjects) {            return StringUtils.toStringArray(this.registeredSingletons);        }    }    // 獲取單例類個數    @Override    public int getSingletonCount() {        synchronized (this.singletonObjects) {            return this.registeredSingletons.size();        }    }    // 設定bean建立狀態    public void setCurrentlyInCreation(String beanName, boolean inCreation) {        Assert.notNull(beanName, "Bean name must not be null");        if (!inCreation) {            this.inCreationCheckExclusions.add(beanName);        }        else {            this.inCreationCheckExclusions.remove(beanName);        }    }    // 當前是否正在被建立    public boolean isCurrentlyInCreation(String beanName) {        Assert.notNull(beanName, "Bean name must not be null");        return (!this.inCreationCheckExclusions.contains(beanName) && isActuallyInCreation(beanName));    }    // 是否在被建立    protected boolean isActuallyInCreation(String beanName) {        return isSingletonCurrentlyInCreation(beanName);    }    //     public boolean isSingletonCurrentlyInCreation(String beanName) {        return this.singletonsCurrentlyInCreation.contains(beanName);    }    // 單例類建立之前呼叫    protected void beforeSingletonCreation(String beanName) {        // 若即將建立的類不在正在建立的集合中,向將要即將建立的類加入        if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {            throw new BeanCurrentlyInCreationException(beanName);        }    }    // 單例類建立之後呼叫    protected void afterSingletonCreation(String beanName) {        // 若即將建立的類正在建立的集合中,向將要即將建立的類移除        if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {            throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");        }    }    // 向disposable註冊例項    public void registerDisposableBean(String beanName, DisposableBean bean) {        synchronized (this.disposableBeans) {            this.disposableBeans.put(beanName, bean);        }    }    // 註冊一個子類 -> 父類    public void registerContainedBean(String containedBeanName, String containingBeanName) {        // A quick check for an existing entry upfront, avoiding synchronization...        Set<String> containedBeans = this.containedBeanMap.get(containingBeanName);        // 已存在 return        if (containedBeans != null && containedBeans.contains(containedBeanName)) {            return;        }        // No entry yet -> fully synchronized manipulation of the containedBeans Set        synchronized (this.containedBeanMap) {            containedBeans = this.containedBeanMap.get(containingBeanName);            if (containedBeans == null) {                containedBeans = new LinkedHashSet<String>(8);// 初始化                // containingBeanName 父類 containedBeans 孩子集合                this.containedBeanMap.put(containingBeanName, containedBeans);            }            containedBeans.add(containedBeanName);// 孩子進窩        }        registerDependentBean(containedBeanName, containingBeanName);// 新增依賴關係·    }    // 給beanName新增dependentBeanName依賴    public void registerDependentBean(String beanName, String dependentBeanName) {        // A quick check for an existing entry upfront, avoiding synchronization...        String canonicalName = canonicalName(beanName);        Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);        // 已存在 ruturn        if (dependentBeans != null && dependentBeans.contains(dependentBeanName)) {            return;        }        // 和上面一樣        synchronized (this.dependentBeanMap) {            dependentBeans = this.dependentBeanMap.get(canonicalName);            if (dependentBeans == null) {                dependentBeans = new LinkedHashSet<String>(8);                this.dependentBeanMap.put(canonicalName, dependentBeans);            }            dependentBeans.add(dependentBeanName);        }        synchronized (this.dependenciesForBeanMap) {            Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName);            if (dependenciesForBean == null) {                dependenciesForBean = new LinkedHashSet<String>(8);                this.dependenciesForBeanMap.put(dependentBeanName, dependenciesForBean);            }            dependenciesForBean.add(canonicalName);        }    }    // 是否依賴關係    protected boolean isDependent(String beanName, String dependentBeanName) {        return isDependent(beanName, dependentBeanName, null);    }    private boolean isDependent(String beanName, String dependentBeanName, Set<String> alreadySeen) {        if (alreadySeen != null && alreadySeen.contains(beanName)) {            return false;        }        String canonicalName = canonicalName(beanName);        Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);        if (dependentBeans == null) {            return false;        }        if (dependentBeans.contains(dependentBeanName)) {            return true;        }        for (String transitiveDependency : dependentBeans) {            if (alreadySeen == null) {                alreadySeen = new HashSet<String>();            }            alreadySeen.add(beanName);            if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {                return true;            }        }        return false;    }    // 是否有依賴bean    protected boolean hasDependentBean(String beanName) {        return this.dependentBeanMap.containsKey(beanName);    }    // 根據beanName獲取所有依賴bean    public String[] getDependentBeans(String beanName) {        Set<String> dependentBeans = this.dependentBeanMap.get(beanName);        if (dependentBeans == null) {            return new String[0];        }        return StringUtils.toStringArray(dependentBeans);    }    // 根據beanName獲取所有所依賴    public String[] getDependenciesForBean(String beanName) {        Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName);        if (dependenciesForBean == null) {            return new String[0];        }        return dependenciesForBean.toArray(new String[dependenciesForBean.size()]);    }    // 銷燬所有單例    public void destroySingletons() {        if (logger.isDebugEnabled()) {            logger.debug("Destroying singletons in " + this);        }        synchronized (this.singletonObjects) {            this.singletonsCurrentlyInDestruction = true;        }        String[] disposableBeanNames;        synchronized (this.disposableBeans) {            disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());        }        for (int i = disposableBeanNames.length - 1; i >= 0; i--) {            destroySingleton(disposableBeanNames[i]);        }        // 清空相關資料        this.containedBeanMap.clear();        this.dependentBeanMap.clear();        this.dependenciesForBeanMap.clear();        synchronized (this.singletonObjects) {            this.singletonObjects.clear();            this.singletonFactories.clear();            this.earlySingletonObjects.clear();            this.registeredSingletons.clear();            this.singletonsCurrentlyInDestruction = false;        }    }    // 銷燬某個單例類    public void destroySingleton(String beanName) {        // Remove a registered singleton of the given name, if any.        removeSingleton(beanName);        // Destroy the corresponding DisposableBean instance.        DisposableBean disposableBean;        synchronized (this.disposableBeans) {            disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);        }        destroyBean(beanName, disposableBean);    }    // 刪除之前新增的各種依賴    protected void destroyBean(String beanName, DisposableBean bean) {        // Trigger destruction of dependent beans first...        Set<String> dependencies = this.dependentBeanMap.remove(beanName);        if (dependencies != null) {            if (logger.isDebugEnabled()) {                logger.debug("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);            }            for (String dependentBeanName : dependencies) {                destroySingleton(dependentBeanName);            }        }        // Actually destroy the bean now...        if (bean != null) {            try {                bean.destroy();            }            catch (Throwable ex) {                logger.error("Destroy method on bean with name '" + beanName + "' threw an exception", ex);            }        }        // Trigger destruction of contained beans...        Set<String> containedBeans = this.containedBeanMap.remove(beanName);        if (containedBeans != null) {            for (String containedBeanName : containedBeans) {                destroySingleton(containedBeanName);            }        }        // Remove destroyed bean from other beans' dependencies.        synchronized (this.dependentBeanMap) {            for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) {                Map.Entry<String, Set<String>> entry = it.next();                Set<String> dependenciesToClean = entry.getValue();                dependenciesToClean.remove(beanName);                if (dependenciesToClean.isEmpty()) {                    it.remove();                }            }        }        // Remove destroyed bean's prepared dependency information.        this.dependenciesForBeanMap.remove(beanName);    }    //     public final Object getSingletonMutex() {        return this.singletonObjects;    }}

AbstractBeanFactory

   =    public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {    // 存放工廠生產的單例集(查詢的結果暫存,像hibernate或mybatis的呼叫快取思路一致)    private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16);    // 返回指定beanFactory工廠的型別    /**        public interface FactoryBean<T> {        T getObject() throws Exception;        boolean isSingleton();              }    */    protected Class<?> getTypeForFactoryBean(final FactoryBean<?> factoryBean) {        try {            // 安全相關檢查 我不去了解了            if (System.getSecurityManager() != null) {                return AccessController.doPrivileged((PrivilegedAction<Class<?>>) () ->                        factoryBean.getObjectType(), getAccessControlContext());            }            else {                return factoryBean.getObjectType();            }        }        catch (Throwable ex) {            // Thrown from the FactoryBean's getObjectType implementation.            logger.warn("FactoryBean threw exception from getObjectType, despite the contract saying " +                    "that it should return null if the type of its object cannot be determined yet", ex);            return null;        }    }    // 根據工廠名返回其生產的物件    @Nullable    protected Object getCachedObjectForFactoryBean(String beanName) {        return this.factoryBeanObjectCache.get(beanName);    }    // 從Factory取物件 第三個引數 是否觸發Post處理    protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {        if (factory.isSingleton() && containsSingleton(beanName)) {            synchronized (getSingletonMutex()) {                Object object = this.factoryBeanObjectCache.get(beanName);                if (object == null) {                    // 從BeanFactory呼叫方法獲取bean                    object = doGetObjectFromFactoryBean(factory, beanName);                    Object alreadyThere = this.factoryBeanObjectCache.get(beanName);                    if (alreadyThere != null) {                        object = alreadyThere;                    }                    else {                        if (shouldPostProcess) {                            try {                                object = postProcessObjectFromFactoryBean(object, beanName);                            }                            catch (Throwable ex) {                                throw new BeanCreationException(beanName,                                        "Post-processing of FactoryBean's singleton object failed", ex);                            }                        }                        // 將物件放入快取單例物件                        this.factoryBeanObjectCache.put(beanName, object);                    }                }                return object;            }        }        else {            Object object = doGetObjectFromFactoryBean(factory, beanName);            if (shouldPostProcess) {                try {                    object = postProcessObjectFromFactoryBean(object, beanName);                }                catch (Throwable ex) {                    throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);                }            }            return object;        }    }    // 從單例工廠獲取bean    private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName)            throws BeanCreationException {        Object object;        try {            // 安全判斷            if (System.getSecurityManager() != null) {                AccessControlContext acc = getAccessControlContext();                try {                    object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->                            factory.getObject(), acc);                }                catch (PrivilegedActionException pae) {                    throw pae.getException();                }            }            else {                object = factory.getObject();            }        }        catch (FactoryBeanNotInitializedException ex) {            throw new BeanCurrentlyInCreationException(beanName, ex.toString());        }        catch (Throwable ex) {            throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);        }        if (object == null) {            if (isSingletonCurrentlyInCreation(beanName)) {                throw new BeanCurrentlyInCreationException(                        beanName, "FactoryBean which is currently in creation returned null from getObject");            }            object = new NullBean();        }        return object;    }    // 交給子類處理    protected Object postProcessObjectFromFactoryBean(Object object, String beanName) throws BeansException {        return object;    }    // beanInstance是BeanFactory型別?是返回    protected FactoryBean<?> getFactoryBean(String beanName, Object beanInstance) throws BeansException {        if (!(beanInstance instanceof FactoryBean)) {            throw new BeanCreationException(beanName,                    "Bean instance of type [" + beanInstance.getClass() + "] is not a FactoryBean");        }        return (FactoryBean<?>) beanInstance;    }    // 移除 beanName    @Override    protected void removeSingleton(String beanName) {        super.removeSingleton(beanName);        this.factoryBeanObjectCache.remove(beanName);    }    // 銷燬 所有    @Override    public void destroySingletons() {        super.destroySingletons();        this.factoryBeanObjectCache.clear();    }    protected AccessControlContext getAccessControlContext() {        return AccessController.getContext();    }}

AbstractBeanFactory

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport    implements ConfigurableBeanFactory {// 父工廠的引用private BeanFactory parentBeanFactory;// 類載入器private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();// 臨時類載入器private ClassLoader tempClassLoader;// 是否快取載入beanprivate boolean cacheBeanMetadata = true;// bean的表達形式private BeanExpressionResolver beanExpressionResolver;// 轉換服務,用來替代屬性編輯器的private ConversionService conversionService;// 屬性編輯登記員集合,容量為4的LinkedHashSetprivate final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet<PropertyEditorRegistrar>(        4);// 型別轉換器private TypeConverter typeConverter;// 預設的屬性編輯器集合private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<Class<?>, Class<? extends PropertyEditor>>(        4);// 嵌入值轉換器集合private final List<StringValueResolver> embeddedValueResolvers = new LinkedList<StringValueResolver>();// bean後置處理器集合private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();// 標記是否有處理器被註冊private boolean hasInstantiationAwareBeanPostProcessors;// 標記是否處理器被銷燬private boolean hasDestructionAwareBeanPostProcessors;// 範圍識別符號和Scope例項的對應的Mapprivate final Map<String, Scope> scopes = new HashMap<String, Scope>(8);// 安全相關(不看了)private SecurityContextProvider securityContextProvider;// 合併後的Bean根定義的集合private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<String, RootBeanDefinition>(        64);// 被建立過得bean集合private final Map<String, Boolean> alreadyCreated = new ConcurrentHashMap<String, Boolean>(        64);// 當前正在建立的原型,當前執行緒相關private final ThreadLocal<Object> prototypesCurrentlyInCreation = new NamedThreadLocal<Object>(        "Prototype beans currently in creation");public AbstractBeanFactory() {}public AbstractBeanFactory(BeanFactory parentBeanFactory) {    this.parentBeanFactory = parentBeanFactory;}// 獲取beanpublic Object getBean(String name) throws BeansException {    return doGetBean(name, null, null, false);}// 獲取beanpublic <T> T getBean(String name, Class<T> requiredType) throws BeansException {    return doGetBean(name, requiredType, null, false);}// 獲取beanpublic Object getBean(String name, Object... args) throws BeansException {    return doGetBean(name, null, args, false);}// 提供建立時需要引數列表的getBeanpublic <T> T getBean(String name, Class<T> requiredType, Object... args)        throws BeansException {    return doGetBean(name, requiredType, args, false);}// 從容器中獲取bean的基本方法。@SuppressWarnings("unchecked")protected <T> T doGetBean(final String name, final Class<T> requiredType,        final Object[] args, boolean typeCheckOnly) throws BeansException {    // 獲取轉化後的beanName    final String beanName = transformedBeanName(name);    Object bean;    // 嘗試從單例集合取這個bean    Object sharedInstance = getSingleton(beanName);    if (sharedInstance != null && args == null) {        // 允許degbug輸出日誌        if (logger.isDebugEnabled()) {            if (isSingletonCurrentlyInCreation(beanName)) {                logger.debug("Returning eagerly cached instance of singleton bean '"                        + beanName                        + "' that is not fully initialized yet - a consequence of a circular reference");            }            else {                logger.debug("Returning cached instance of singleton bean '"                        + beanName + "'");            }        }        //// 根據給定的例項是否為工廠Bean,返回它自己或工廠Bean建立的例項        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);    }    else {        if (isPrototypeCurrentlyInCreation(beanName)) {// 如果正在被建立,就丟擲異常            throw new BeanCurrentlyInCreationException(beanName);        }        BeanFactory parentBeanFactory = getParentBeanFactory();// 取本容器的父容器        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {// 若存在父容器,且本容器不存在對應的Bean定義            String nameToLookup = originalBeanName(name);// 取原始的Bean名            if (args != null) {// 若引數列表存在                // 那麼用父容器根據原始Bean名和引數列表返回                return (T) parentBeanFactory.getBean(nameToLookup, args);            }            else {                // 引數列表不要求,那就直接根據原始名稱和要求的型別返回                return parentBeanFactory.getBean(nameToLookup, requiredType);            }        }        // 如果不需要型別檢查,標記其已經被建立        if (!typeCheckOnly) {            markBeanAsCreated(beanName);        }        // 根據beanName取其根Bean定義        final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);        checkMergedBeanDefinition(mbd, beanName, args);        String[] dependsOn = mbd.getDependsOn();// 得到這個根定義的所有依賴        if (dependsOn != null) {            for (String dependsOnBean : dependsOn) {                getBean(dependsOnBean);// 註冊這個Bean                // 註冊一個Bean和依賴於它的Bean(後引數依賴前引數)                registerDependentBean(dependsOnBean, beanName);            }        }        // 如果Bean定義是單例,就在返回單例        if (mbd.isSingleton()) {            sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {                public Object getObject() throws BeansException {                    try {                        return createBean(beanName, mbd, args);                    }                    catch (BeansException ex) {                        destroySingleton(beanName);                        throw ex;                    }                }            });            // 根據給定的例項是否為工廠Bean,返回它自己或工廠Bean建立的例項            bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);        }        // 如果是原型        else if (mbd.isPrototype()) {            // It's a prototype -> create a new instance.            Object prototypeInstance = null;            try {                beforePrototypeCreation(beanName);// 原型建立前,與當前執行緒繫結                prototypeInstance = createBean(beanName, mbd, args);            }            finally {                afterPrototypeCreation(beanName);// 原型建立後,與當前執行緒解除繫結            }            bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);        }        else {// 既不是單例又不是原型的情況            String scopeName = mbd.getScope();            final Scope scope = this.scopes.get(scopeName);// 得到範圍            if (scope == null) {                throw new IllegalStateException(                        "No Scope registered for scope '" + scopeName + "'");            }            try {// 根據範圍建立例項                Object scopedInstance = scope.get(beanName,                        new ObjectFactory<Object>() {                            public Object getObject() throws BeansException {                                beforePrototypeCreation(beanName);                                try {                                    return createBean(beanName, mbd, args);// 原型建立前,與當前執行緒繫結                                }                                finally {                                    //// 原型建立後,與當前執行緒解除繫結                                    afterPrototypeCreation(beanName);                                }                            }                        });                // 根據給定的例項是否為工廠Bean,返回它自己或工廠Bean建立的例項                bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);            }            catch (IllegalStateException ex) {                throw new BeanCreationException(beanName,                        "Scope '" + scopeName                                + "' is not active for the current thread; "                                + "consider defining a scoped proxy for this bean if you intend to refer to it from a singleton",                        ex);            }        }    }    // 判斷要求的型別是否和Bean例項的型別正在匹配    if (requiredType != null && bean != null            && !requiredType.isAssignableFrom(bean.getClass())) {        try {            return getTypeConverter().convertIfNecessary(bean, requiredType);// 轉換型別,不丟擲異常就說明型別匹配        }        catch (TypeMismatchException ex) {            if (logger.isDebugEnabled()) {                logger.debug(                        "Failed to convert bean '" + name + "' to required type ["                                + ClassUtils.getQualifiedName(requiredType) + "]",                        ex);            }            throw new BeanNotOfRequiredTypeException(name, requiredType,                    bean.getClass());        }    }    return (T) bean;}// 判斷本容器是否包含指定beanpublic boolean containsBean(String name) {    String beanName = transformedBeanName(name);    // (如果是否包含單例 或 包含Bean定義)且 (為工廠Bean的產物 或 本身就是工廠bean),就返回true    if (containsSingleton(beanName) || containsBeanDefinition(beanName)) {        return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name));    }    // 如果不包含單例且不包含Bean定義,就從父類去查詢    BeanFactory parentBeanFactory = getParentBeanFactory();    return (parentBeanFactory != null            && parentBeanFactory.containsBean(originalBeanName(name)));}// 判斷指定Bean是否為單例public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {    String beanName = transformedBeanName(name);    Object beanInstance = getSingleton(beanName, false);// 首先從單例集合中取    if (beanInstance != null) {// 取不到,就判斷它是不是FactoryBean的例項        if (beanInstance instanceof FactoryBean) { // 如果是,要求它是工廠Bean產生的例項或這個工廠bean是單例            return (BeanFactoryUtils.isFactoryDereference(name)                    || ((FactoryBean<?>) beanInstance).isSingleton());        }        else {// 如果不是,要求它不是工廠Bean產生的例項            return !BeanFactoryUtils.isFactoryDereference(name);        }    } // 若雖然取不到,但是單例集合中包含它的名字,說明它是單例    else if (containsSingleton(beanName)) {        return true;    }    else {        // 從父工廠中去查詢Bean定義        BeanFactory parentBeanFactory = getParentBeanFactory();        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {            // 父工廠找不到Bean定義,那就在父工廠根據原始名去查是否為單例            return parentBeanFactory.isSingleton(originalBeanName(name));        }        // 返回一個合併後的根Bean定義        RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);        // In case of FactoryBean, return singleton status of created object if not a        // dereference.        // 若該根定義是單例        if (mbd.isSingleton()) {            if (isFactoryBean(beanName, mbd)) { // 若該根定義為工廠Bean                if (BeanFactoryUtils.isFactoryDereference(name)) {// 判斷是否為工廠產生的例項                    return true;                }                // 取對應的工廠,判斷該工廠Bean是否為單例                FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(                        FACTORY_BEAN_PREFIX + beanName);                return factoryBean.isSingleton();            }            else { // 是否不為工廠Bean產生的例項(此時,即,該根定義不為工廠Bean,且不為工廠Bean產生的例項的時候,由於根定義是單例,那麼它就是單例)                return !BeanFactoryUtils.isFactoryDereference(name);            }        }        else {            return false;        }    }}// 判斷是否為原型public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {    String beanName = transformedBeanName(name);    BeanFactory parentBeanFactory = getParentBeanFactory();// 得到父工廠    // 若父工廠中的定義為原型,就為原型    if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {        return parentBeanFactory.isPrototype(originalBeanName(name));    }    // 若合併後的根定義為原型,且不是工廠Bean產生的例項、或本身是工廠Bean,那麼就為原型    RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);    if (mbd.isPrototype()) {        return (!BeanFactoryUtils.isFactoryDereference(name)                || isFactoryBean(beanName, mbd));    }    else {        if (BeanFactoryUtils.isFactoryDereference(name)) {// 若為工廠Bean產生的例項            return false;        }        if (isFactoryBean(beanName, mbd)) {// 若為工廠Bean,取它產生的Bean,判斷SmartFactoryBean            final FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(                    FACTORY_BEAN_PREFIX + beanName);            if (System.getSecurityManager() != null) {                return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {                    public Boolean run() {                        return ((factoryBean instanceof SmartFactoryBean                                && ((SmartFactoryBean<?>) factoryBean).isPrototype())                                || !factoryBean.isSingleton());                    }                }, getAccessControlContext());            }            else {                return ((factoryBean instanceof SmartFactoryBean                        && ((SmartFactoryBean<?>) factoryBean).isPrototype())                        || !factoryBean.isSingleton());            }        }        else {            return false;        }    }}// 判斷型別是否匹配public boolean isTypeMatch(String name, Class<?> targetType)        throws NoSuchBeanDefinitionException {    String beanName = transformedBeanName(name);    Class<?> typeToMatch = (targetType != null ? targetType : Object.class);    Object beanInstance = getSingleton(beanName, false);// 取name對應的單例    if (beanInstance != null) {        if (beanInstance instanceof FactoryBean) {// 若為工廠Bean            // 若不是工廠Bean產生的例項            if (!BeanFactoryUtils.isFactoryDereference(name)) {                // 取工廠Bean的型別與targetType進行對比                Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance);                return (type != null && ClassUtils.isAssignable(typeToMatch, type));            }            else {                return ClassUtils.isAssignableValue(typeToMatch, beanInstance);            }        }        // 不是工廠Bean,那就直接判斷        else {            return !BeanFactoryUtils.isFactoryDereference(name)                    && ClassUtils.isAssignableValue(typeToMatch, beanInstance);        }    }    // 單例表中,對應的Key沒有值,也不包含Bean定義,說明沒有註冊,返回false    else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {        return false;    }    // 以下是包含Bean定義的情況    else {        // 先查父類的Bean定義        BeanFactory parentBeanFactory = getParentBeanFactory();        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {            // No bean definition found in this factory -> delegate to parent.            return parentBeanFactory.isTypeMatch(originalBeanName(name), targetType);        }        // 直接查合併後的根定義        RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);        // 構建型別陣列        Class[] typesToMatch = (FactoryBean.class.equals(typeToMatch)                ? new Class[] { typeToMatch }                : new Class[] { FactoryBean.class, typeToMatch });        // Check decorated bean definition, if any: We assume it'll be easier        // to determine the decorated bean's type than the proxy's type.        // 得到Bean定義的持有者        BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();        if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {// 若為Bean工廠生成的例項,先得到根定義            RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(),                    dbd.getBeanDefinition(), mbd);            Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd,                    typesToMatch);// 得到預測的根定義            if (targetClass != null                    && !FactoryBean.class.isAssignableFrom(targetClass)) {                return typeToMatch.isAssignableFrom(targetClass);            }        }        Class<?> beanType = predictBeanType(beanName, mbd, typesToMatch);// 預測後的型別        if (beanType == null) {            return false;        }        if (FactoryBean.class.isAssignableFrom(beanType)) {// BeanFactory是否為其子類            if (!BeanFactoryUtils.isFactoryDereference(name)) {// 若不為工廠Bean的產物                // If it's a FactoryBean, we want to look at what it creates, not the                // factory class.                beanType = getTypeForFactoryBean(beanName, mbd);                if (beanType == null) {                    return false;                }            }        }        else if (BeanFactoryUtils.isFactoryDereference(name)) {// 若為工廠類Bean的產物            beanType = predictBeanType(beanName, mbd, FactoryBean.class);// 預測型別            if (beanType == null || !FactoryBean.class.isAssignableFrom(beanType)) {                return false;            }        }        return typeToMatch.isAssignableFrom(beanType);    }}// 返回型別public Class<?> getType(String name) throws NoSuchBeanDefinitionException {    String beanName = transformedBeanName(name);    // Check manually registered singletons.    Object beanInstance = getSingleton(beanName, false);    if (beanInstance != null) {        if (beanInstance instanceof FactoryBean                && !BeanFactoryUtils.isFactoryDereference(name)) {            return getTypeForFactoryBean((FactoryBean<?>) beanInstance);        }        else {            return beanInstance.getClass();        }    }    else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {        // null instance registered        return null;    }    else {        // No singleton instance found -> check bean definition.        BeanFactory parentBeanFactory = getParentBeanFactory();        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {            // No bean definition found in this factory -> delegate to parent.            return parentBeanFactory.getType(originalBeanName(name));        }        RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);        // Check decorated bean definition, if any: We assume it'll be easier        // to determine the decorated bean's type than the proxy's type.        BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();        if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {            RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(),                    dbd.getBeanDefinition(), mbd);            Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd);            if (targetClass != null                    && !FactoryBean.class.isAssignableFrom(targetClass)) {                return targetClass;            }        }        Class<?> beanClass = predictBeanType(beanName, mbd);        // Check bean class whether we're dealing with a FactoryBean.        if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) {            if (!BeanFactoryUtils.isFactoryDereference(name)) {                // If it's a FactoryBean, we want to look at what it creates, not at                // the factory class.                return getTypeForFactoryBean(beanName, mbd);            }            else {                return beanClass;            }        }        else {            return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null);        }    }}// 重寫了,得到別名的方法。@Overridepublic String[] getAliases(String name) {    String beanName = transformedBeanName(name);    List<String> aliases = new ArrayList<String>();    boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX);    String fullBeanName = beanName;    if (factoryPrefix) {        fullBeanName = FACTORY_BEAN_PREFIX + beanName;    }    if (!fullBeanName.equals(name)) {        aliases.add(fullBeanName);    }    String[] retrievedAliases = super.getAliases(beanName);    for (String retrievedAlias : retrievedAliases) {        String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") + retrievedAlias;        if (!alias.equals(name)) {            aliases.add(alias);        }    }    if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) {        BeanFactory parentBeanFactory = getParentBeanFactory();        if (parentBeanFactory != null) {            aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName)));        }    }    return StringUtils.toStringArray(aliases);}// ---------------------------------------------------------------------// Implementation of HierarchicalBeanFactory interface// ---------------------------------------------------------------------// 返回本Bean工廠的父Bean工廠public BeanFactory getParentBeanFactory() {    return this.parentBeanFactory;}// 是否在本容器中(就是說,並不是工廠bean生產出來的)public boolean containsLocalBean(String name) {    String beanName = transformedBeanName(name); // 轉換後的名字    // (是否為單例或有對應的Bean定義) 且(不是工廠Bean生產出來的 或 本身就是工廠bean)    return ((containsSingleton(beanName) || containsBeanDefinition(beanName))            && (!BeanFactoryUtils.isFactoryDereference(name)                    || isFactoryBean(beanName)));}// ---------------------------------------------------------------------// Implementation of ConfigurableBeanFactory interface// ---------------------------------------------------------------------public void setParentBeanFactory(BeanFactory parentBeanFactory) {    if (this.parentBeanFactory != null            && this.parentBeanFactory != parentBeanFactory) {        throw new IllegalStateException("Already associated with parent BeanFactory: "                + this.parentBeanFactory);    }    this.parentBeanFactory = parentBeanFactory;}public void setBeanClassLoader(ClassLoader beanClassLoader) {    this.beanClassLoader = (beanClassLoader != null ? beanClassLoader            : ClassUtils.getDefaultClassLoader());}public ClassLoader getBeanClassLoader() {    return this.beanClassLoader;}public void setTempClassLoader(ClassLoader tempClassLoader) {    this.tempClassLoader = tempClassLoader;}public ClassLoader getTempClassLoader() {    return this.tempClassLoader;}public void setCacheBeanMetadata(boolean cacheBeanMetadata) {    this.cacheBeanMetadata = cacheBeanMetadata;}public boolean isCacheBeanMetadata() {    return this.cacheBeanMetadata;}public void setBeanExpressionResolver(BeanExpressionResolver resolver) {    this.beanExpressionResolver = resolver;}public BeanExpressionResolver getBeanExpressionResolver() {    return this.beanExpressionResolver;}public void setConversionService(ConversionService conversionService) {    this.conversionService = conversionService;}public ConversionService getConversionService() {    return this.conversionService;}public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) {    Assert.notNull(registrar, "PropertyEditorRegistrar must not be null");    this.propertyEditorRegistrars.add(registrar);}/** * Return the set of PropertyEditorRegistrars. */public Set<PropertyEditorRegistrar> getPropertyEditorRegistrars() {    return this.propertyEditorRegistrars;}public void registerCustomEditor(Class<?> requiredType,        Class<? extends PropertyEditor> propertyEditorClass) {    Assert.notNull(requiredType, "Required type must not be null");    Assert.isAssignable(PropertyEditor.class, propertyEditorClass);    this.customEditors.put(requiredType, propertyEditorClass);}public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) {    registerCustomEditors(registry);}/** * Return the map of custom editors, with Classes as keys and PropertyEditor classes * as values. */public Map<Class<?>, Class<? extends PropertyEditor>> getCustomEditors() {    return this.customEditors;}public void setTypeConverter(TypeConverter typeConverter) {    this.typeConverter = typeConverter;}// 得到通用的型別轉換器protected TypeConverter getCustomTypeConverter() {    return this.typeConverter;}// 得到型別轉換器public TypeConverter getTypeConverter() {    TypeConverter customConverter = getCustomTypeConverter();    if (customConverter != null) {        return customConverter;    }    else {// 若本容器未註冊型別轉換器,就建立一個簡單的型別轉換器        SimpleTypeConverter typeConverter = new SimpleTypeConverter();        typeConverter.setConversionService(getConversionService());        registerCustomEditors(typeConverter);        return typeConverter;    }}public void addEmbeddedValueResolver(StringValueResolver valueResolver) {    Assert.notNull(valueResolver, "StringValueResolver must not be null");    this.embeddedValueResolvers.add(valueResolver);}public String resolveEmbeddedValue(String value) {    String result = value;    for (StringValueResolver resolver : this.embeddedValueResolvers) {        if (result == null) {            return null;        }        result = resolver.resolveStringValue(result);    }    return result;}public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {    Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");    this.beanPostProcessors.remove(beanPostProcessor);    this.beanPostProcessors.add(beanPostProcessor);    if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {        this.hasInstantiationAwareBeanPostProcessors = true;    }    if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {        this.hasDestructionAwareBeanPostProcessors = true;    }}public int getBeanPostProcessorCount() {    return this.beanPostProcessors.size();}/** * Return the list of BeanPostProcessors that will get applied to beans created with * this factory. */public List<BeanPostProcessor> getBeanPostProcessors() {    return this.beanPostProcessors;}/** * Return whether this factory holds a InstantiationAwareBeanPostProcessor that will * get applied to singleton beans on shutdown. *  * @see #addBeanPostProcessor * @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor */protected boolean hasInstantiationAwareBeanPostProcessors() {    return this.hasInstantiationAwareBeanPostProcessors;}/** * Return whether this factory holds a DestructionAwareBeanPostProcessor that will get * applied to singleton beans on shutdown. *  * @see #addBeanPostProcessor * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor */protected boolean hasDestructionAwareBeanPostProcessors() {    return this.hasDestructionAwareBeanPostProcessors;}public void registerScope(String scopeName, Scope scope) {    Assert.notNull(scopeName, "Scope identifier must not be null");    Assert.notNull(scope, "Scope must not be null");    if (SCOPE_SINGLETON.equals(scopeName) || SCOPE_PROTOTYPE.equals(scopeName)) {        throw new IllegalArgumentException(                "Cannot replace existing scopes 'singleton' and 'prototype'");    }    this.scopes.put(scopeName, scope);}public String[] getRegisteredScopeNames() {    return StringUtils.toStringArray(this.scopes.keySet());}public Scope getRegisteredScope(String scopeName) {    Assert.notNull(scopeName, "Scope identifier must not be null");    return this.scopes.get(scopeName);}/** * Set the security context provider for this bean factory. If a security manager is * set, interaction with the user code will be executed using the privileged of the * provided security context. */public void setSecurityContextProvider(SecurityContextProvider securityProvider) {    this.securityContextProvider = securityProvider;}/** * Delegate the creation of the access control context to the * {@link #setSecurityContextProvider SecurityContextProvider}. */@Overridepublic AccessControlContext getAccessControlContext() {    return (this.securityContextProvider != null            ? this.securityContextProvider.getAccessControlContext()            : AccessController.getContext());}public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {    Assert.notNull(otherFactory, "BeanFactory must not be null");    setBeanClassLoader(otherFactory.getBeanClassLoader());    setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());    setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());    if (otherFactory instanceof AbstractBeanFactory) {        AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory;        this.customEditors.putAll(otherAbstractFactory.customEditors);        this.propertyEditorRegistrars.addAll(                otherAbstractFactory.propertyEditorRegistrars);        this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors);        this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors                || otherAbstractFactory.hasInstantiationAwareBeanPostProcessors;        this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors                || otherAbstractFactory.hasDestructionAwareBeanPostProcessors;        this.scopes.putAll(otherAbstractFactory.scopes);        this.securityContextProvider = otherAbstractFactory.securityContextProvider;    }    else {        setTypeConverter(otherFactory.getTypeConverter());    }}// 返回合併後的bean定義(父Bean定義和子Bean定義合併)public BeanDefinition getMergedBeanDefinition(String name) throws BeansException {    String beanName = transformedBeanName(name);    // Efficiently check whether bean definition exists in this factory.    // 若Bean定義不存在,且本容器父工廠為ConfigurableBeanFactory的例項,讓父工廠來呼叫這個方法    if (!containsBeanDefinition(beanName)            && getParentBeanFactory() instanceof ConfigurableBeanFactory) {        return ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(                beanName);    }    // 否則直接從本地合併後的Bean定義中取    return getMergedLocalBeanDefinition(beanName);}public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {    String beanName = transformedBeanName(name);    Object beanInstance = getSingleton(beanName, false);    if (beanInstance != null) {        return (beanInstance instanceof FactoryBean);    }    else if (containsSingleton(beanName)) {        // null instance registered        return false;    }    // No singleton instance found -> check bean definition.    if (!containsBeanDefinition(beanName)            && getParentBeanFactory() instanceof ConfigurableBeanFactory) {        // No bean definition found in this factory -> delegate to parent.        return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);    }    return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));}@Overridepublic boolean isActuallyInCreation(String beanName) {    return isSingletonCurrentlyInCreation(beanName)            || isPrototypeCurrentlyInCreation(beanName);}// 判斷指定的原型是否正在被建立protected boolean isPrototypeCurrentlyInCreation(String beanName) {    Object curVal = this.prototypesCurrentlyInCreation.get();    return (curVal != null && (curVal.equals(beanName)            || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));}// 原型建立前回撥,需要子類重寫@SuppressWarnings("unchecked")protected void beforePrototypeCreation(String beanName) {    Object curVal = this.prototypesCurrentlyInCreation.get();    if (curVal == null) {// 原型建立狀態與當前執行緒繫結        this.prototypesCurrentlyInCreation.set(beanName);    }    else if (curVal instanceof String) {        Set<String> beanNameSet = new HashSet<String>(2);        beanNameSet.add((String) curVal);        beanNameSet.add(beanName);        this.prototypesCurrentlyInCreation.set(beanNameSet);    }    // 這裡多餘了。。。    else {        Set<String> beanNameSet = (Set<String>) curVal;        beanNameSet.add(beanName);    }}// 建立原型後,從當前執行緒解除繫結@SuppressWarnings("unchecked")protected void afterPrototypeCreation(String beanName) {    Object curVal = this.prototypesCurrentlyInCreation.get();    if (curVal instanceof String) {        this.prototypesCurrentlyInCreation.remove();    }    else if (curVal instanceof Set) {        Set<String> beanNameSet = (Set<String>) curVal;        beanNameSet.remove(beanName);        if (beanNameSet.isEmpty()) {            this.prototypesCurrentlyInCreation.remove();        }    }}public void destroyBean(String beanName, Object beanInstance) {    destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName));}/** * Destroy the given bean instance (usually a prototype instance obtained from this * factory) according to the given bean definition. *  * @param beanName the name of the bean definition * @param beanInstance the bean instance to destroy * @param mbd the merged bean definition */protected void destroyBean(String beanName, Object beanInstance,        RootBeanDefinition mbd) {    new DisposableBeanAdapter(beanInstance, beanName, mbd, getBeanPostProcessors(),            getAccessControlContext()).destroy();}public void destroyScopedBean(String beanName) {    RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);    if (mbd.isSingleton() || mbd.isPrototype()) {        throw new IllegalArgumentException("Bean name '" + beanName                + "' does not correspond to an object in a mutable scope");    }    String scopeName = mbd.getScope();    Scope scope = this.scopes.get(scopeName);    if (scope == null) {        throw new IllegalStateException(                "No Scope SPI registered for scope '" + scopeName + "'");    }    Object bean = scope.remove(beanName);    if (bean != null) {        destroyBean(beanName, bean, mbd);    }}// ---------------------------------------------------------------------// Implementation methods// ---------------------------------------------------------------------// 變換後的Bean名稱(先去掉BeanFactory字首,然後在aliasMap中取標準名)protected String transformedBeanName(String name) {    return canonicalName(BeanFactoryUtils.transformedBeanName(name));}// 返回原始的Bean名protected String originalBeanName(String name) {    String beanName = transformedBeanName(name);    if (name.startsWith(FACTORY_BEAN_PREFIX)) {        beanName = FACTORY_BEAN_PREFIX + beanName;    }    return beanName;}/** * Initialize the given BeanWrapper with the custom editors registered with this * factory. To be called for BeanWrappers that will create and populate bean * instances. * <p> * The default implementation delegates to {@link #registerCustomEditors}. Can be * overridden in subclasses. *  * @param bw the BeanWrapper to initialize */protected void initBeanWrapper(BeanWrapper bw) {    bw.setConversionService(getConversionService());    registerCustomEditors(bw);}/** * Initialize the given PropertyEditorRegistry with the custom editors that have been * registered with this BeanFactory. * <p> * To be called for BeanWrappers that will create and populate bean instances, and for * SimpleTypeConverter used for constructor argument and factory method type * conversion. *  * @param registry the PropertyEditorRegistry to initialize */protected void registerCustomEditors(PropertyEditorRegistry registry) {    PropertyEditorRegistrySupport registrySupport = (registry instanceof PropertyEditorRegistrySupport            ? (PropertyEditorRegistrySupport) registry : null);    if (registrySupport != null) {        registrySupport.useConfigValueEditors();    }    if (!this.propertyEditorRegistrars.isEmpty()) {        for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {            try {                registrar.registerCustomEditors(registry);            }            catch (BeanCreationException ex) {                Throwable rootCause = ex.getMostSpecificCause();                if (rootCause instanceof BeanCurrentlyInCreationException) {                    BeanCreationException bce = (BeanCreationException) rootCause;                    if (isCurrentlyInCreation(bce.getBeanName())) {                        if (logger.isDebugEnabled()) {                            logger.debug("PropertyEditorRegistrar ["                                    + registrar.getClass().getName()                                    + "] failed because it tried to obtain currently created bean '"                                    + ex.getBeanName() + "': " + ex.getMessage());                        }                        onSuppressedException(ex);                        continue;                    }                }                throw ex;            }        }    }    if (!this.customEditors.isEmpty()) {        for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : this.customEditors.entrySet()) {            Class<?> requiredType = entry.getKey();            Class<? extends PropertyEditor> editorClass = entry.getValue();            registry.registerCustomEditor(requiredType,                    BeanUtils.instantiateClass(editorClass));        }    }}// 返回一個合併後的根Bean定義(父Bean定義和子Bean定義合併)(從當前容器取)protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName)        throws BeansException {    // Quick check on the concurrent map first, with minimal locking.    RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);// 首先直接從合併根定義集合中取    if (mbd != null) {        return mbd;    }    // 根據bean名和其對應的Bean定義,取其根Bean根定義    return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));}// 根據Bean名和Bean定義取其Bean根定義protected RootBeanDefinition getMergedBeanDefinition(String beanName,        BeanDefinition bd) throws BeanDefinitionStoreException {    return getMergedBeanDefinition(beanName, bd, null);// 呼叫過載方法}// 根據Bean名稱返回根定義(若給定的Bean定義為子Bean定義,那麼合併它的父Bean定義)protected RootBeanDefinition getMergedBeanDefinition(String beanName,        BeanDefinition bd, BeanDefinition containingBd)        throws BeanDefinitionStoreException {    synchronized (this.mergedBeanDefinitions) {        RootBeanDefinition mbd = null;        // 若給定的Bean定義並沒有包含子Bean定義,那麼直接根據Bean名取根定義        if (containingBd == null) {            mbd = this.mergedBeanDefinitions.get(beanName);        }        if (mbd == null) {// 若取不到            if (bd.getParentName() == null) {// 若Bean定義沒有父類,就很簡單了                if (bd instanceof RootBeanDefinition) {// 若Bean定義是RootBeanDefinition的例項,克隆、強轉後返回                    mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();                }                else {// 否則,根據Bean定義,來構造一個根Bean定義                    mbd = new RootBeanDefinition(bd);                }            }            else {// 若Bean定義有父類                    // Child bean definition: needs to be merged with parent.                BeanDefinition pbd;                try {                    String parentBeanName = transformedBeanName(bd.getParentName());// 取其父Bean定義的名字                    if (!beanName.equals(parentBeanName)) {// 若Bean名字並不是bd的父Bean的名字                        pbd = getMergedBeanDefinition(parentBeanName);// 根據父Bean定義名稱來返回合併後的bean定義                    }                    else {// 如果beanName對應的Bean就是bd的父Bean                        if (getParentBeanFactory() instanceof ConfigurableBeanFactory) {// 若父Bean工廠為ConfigurableBeanFactory的例項                            // 那麼強轉成ConfigurableBeanFactory後再呼叫合併方法                            pbd = ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(                                    parentBeanName);                        }                        else {// 若父Bean工廠不是ConfigurableBeanFactory的例項,就丟擲異常                            throw new NoSuchBeanDefinitionException(                                    bd.getParentName(),                                    "Parent name '" + bd.getParentName()                                            + "' is equal to bean name '" + beanName                                            + "': cannot be resolved without an AbstractBeanFactory parent");                        }                    }                }                catch (NoSuchBeanDefinitionException ex) {                    throw new BeanDefinitionStoreException(                            bd.getResourceDescription(), beanName,                            "Could not resolve parent bean definition '"                                    + bd.getParentName() + "'",                            ex);                }                // 深度複製                mbd = new RootBeanDefinition(pbd);// 根據Bean定義生成一個根Bean定義                mbd.overrideFrom(bd);// 將Bean定義的屬性複製進自己的定義(根Bean定義)中            }            if (!StringUtils.hasLength(mbd.getScope())) {// 如果根Bean定義未設定範圍                mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);// 那麼設定其範圍為單例            }            // 若本根Bean定義包含Bean定義、本根Bean定義為單例且包含的Bean定義並不是單例            if (containingBd != null && !containingBd.isSingleton()                    && mbd.isSingleton()) {                mbd.setScope(containingBd.getScope());// 那麼將本根Bean定義的範圍設定為包含的Bean定義的範圍            }            // 若本根Bean定義不包含Bean定義,且是快取Bean後設資料(重寫前均為true)且Bean定義是否有資格快取(預設實現是,這個Bean已經建立便有資格)            if (containingBd == null && isCacheBeanMetadata()                    && isBeanEligibleForMetadataCaching(beanName)) {                this.mergedBeanDefinitions.put(beanName, mbd);// 放進mergedBeanDefinitions中            }        }        return mbd;    }}// 檢查Bean定義,丟擲異常protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName,        Object[] args) throws BeanDefinitionStoreException {    if (mbd.isAbstract()) {        throw new BeanIsAbstractException(beanName);    }    if (args != null && !mbd.isPrototype()) {        throw new BeanDefinitionStoreException(                "Can only specify arguments for the getBean method when referring to a prototype bean definition");    }}/** * Remove the merged bean definition for the specified bean, recreating it on next * access. *  * @param beanName the bean name to clear the merged definition for */protected void clearMergedBeanDefinition(String beanName) {    this.mergedBeanDefinitions.remove(beanName);}// 解析型別,處理異常protected Class<?> resolveBeanClass(final RootBeanDefinition mbd, String beanName,        final Class<?>... typesToMatch) throws CannotLoadBeanClassException {    try {        if (mbd.hasBeanClass()) {            return mbd.getBeanClass();        }        if (System.getSecurityManager() != null) {            return AccessController.doPrivileged(                    new PrivilegedExceptionAction<Class<?>>() {                        public Class<?> run() throws Exception {                            return doResolveBeanClass(mbd, typesToMatch);                        }                    }, getAccessControlContext());        }        else {            return doResolveBeanClass(mbd, typesToMatch);        }    }    catch (PrivilegedActionException pae) {        ClassNotFoundException ex = (ClassNotFoundException) pae.getException();        throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName,                mbd.getBeanClassName(), ex);    }    catch (ClassNotFoundException ex) {        throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName,                mbd.getBeanClassName(), ex);    }    catch (LinkageError err) {        throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName,                mbd.getBeanClassName(), err);    }}// 真正的解析型別private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch)        throws ClassNotFoundException {    if (!ObjectUtils.isEmpty(typesToMatch)) {        ClassLoader tempClassLoader = getTempClassLoader();// 找到臨時的類載入器        if (tempClassLoader != null) {            if (tempClassLoader instanceof DecoratingClassLoader) {// 若為裝飾類載入器                DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader;                for (Class<?> typeToMatch : typesToMatch) {                    dcl.excludeClass(typeToMatch.getName());                }            }            String className = mbd.getBeanClassName();            return (className != null ? ClassUtils.forName(className, tempClassLoader)                    : null);        }    }    return mbd.resolveBeanClass(getBeanClassLoader());}/** * Evaluate the given String as contained in a bean definition, potentially resolving * it as an expression. *  * @param value the value to check * @param beanDefinition the bean definition that the value comes from * @return the resolved value * @see #setBeanExpressionResolver */protected Object evaluateBeanDefinitionString(String value,        BeanDefinition beanDefinition) {    if (this.beanExpressionResolver == null) {        return value;    }    Scope scope = (beanDefinition != null            ? getRegisteredScope(beanDefinition.getScope()) : null);    return this.beanExpressionResolver.evaluate(value,            new BeanExpressionContext(this, scope));}// 預測型別protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd,        Class<?>... typesToMatch) {    // 若根Bena定義的工廠方法名存在,說明它是工廠Bean建立的,無法預測型別?    if (mbd.getFactoryMethodName() != null) {        return null;    }    // 否則,解析Bean的Class    return resolveBeanClass(mbd, beanName, typesToMatch);}/** * Check whether the given bean is defined as a {@link FactoryBean}. *  * @param beanName the name of the bean * @param mbd the corresponding bean definition */protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) {    Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class);    return (beanType != null && FactoryBean.class.isAssignableFrom(beanType));}// 返回工廠Bean的型別protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {    if (!mbd.isSingleton()) {        return null;    }    try {        FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName,                FactoryBean.class, null, true);        return getTypeForFactoryBean(factoryBean);    }    catch (BeanCreationException ex) {        // Can only happen when getting a FactoryBean.        if (logger.isDebugEnabled()) {            logger.debug(                    "Ignoring bean creation exception on FactoryBean type check: "                            + ex);        }        onSuppressedException(ex);        return null;    }}// 標記這個Bean已經被建立protected void markBeanAsCreated(String beanName) {    this.alreadyCreated.put(beanName, Boolean.TRUE);}/** * Determine whether the specified bean is eligible for having its bean definition * metadata cached. *  * @param beanName the name of the bean * @return {@code true} if the bean's metadata may be cached at this point already */// 若本根Bean定義包含Bean元定義作為快取,這個方法應被之類覆蓋,這裡僅判斷Bean是否已經被建立protected boolean isBeanEligibleForMetadataCaching(String beanName) {    return this.alreadyCreated.containsKey(beanName);}/** * Remove the singleton instance (if any) for the given bean name, but only if it * hasn't been used for other purposes than type checking. *  * @param beanName the name of the bean * @return {@code true} if actually removed, {@code false} otherwise */protected boolean removeSingletonIfCreatedForTypeCheckOnly(String beanName) {    if (!this.alreadyCreated.containsKey(beanName)) {        removeSingleton(beanName);        return true;    }    else {        return false;    }}// 返回它自己或工廠Bean建立的例項protected Object getObjectForBeanInstance(Object beanInstance, String name,        String beanName, RootBeanDefinition mbd) {    // 如果這個Bean是工廠Bean建立的 且 這個Bean例項並不是FactoryBean例項,拋異常    if (BeanFactoryUtils.isFactoryDereference(name)            && !(beanInstance instanceof FactoryBean)) {        throw new BeanIsNotAFactoryException(transformedBeanName(name),                beanInstance.getClass());    }    // 如果這個Bean例項並不是FactoryBean例項 或 這個Bean是工廠Bean建立的,直接返回    if (!(beanInstance instanceof FactoryBean)            || BeanFactoryUtils.isFactoryDereference(name)) {        return beanInstance;    }    // ——————————以下都是 這個Bean例項是FactoryBean例項的情況    Object object = null;    if (mbd == null) {// 若根Bean定義為空,取這個BeanFactory所生產的例項        object = getCachedObjectForFactoryBean(beanName);    }    if (object == null) {// 若取不到,那麼手動取        FactoryBean<?> factory = (FactoryBean<?>) beanInstance;// 把這個例項轉化成一個FactoryBean        // Caches object obtained from FactoryBean if it is a singleton.        if (mbd == null && containsBeanDefinition(beanName)) {// 若根Bean定義為空,但是容器內有Bean定義            mbd = getMergedLocalBeanDefinition(beanName);// 返回合併後的Bean定義        }        boolean synthetic = (mbd != null && mbd.isSynthetic());// 標記這個Bean定義是合併的        object = getObjectFromFactoryBean(factory, beanName, !synthetic);// 從工廠Bean中取    }    return object;}// 判斷給定的Bean是否被使用過public boolean isBeanNameInUse(String beanName) {    // 若是別名 或 並非工廠bean生產出來的 或 被其他某個bean所依賴,那麼判斷其被使用過    return isAlias(beanName) || containsLocalBean(beanName)            || hasDependentBean(beanName);}/** * Determine whether the given bean requires destruction on shutdown. * <p> * The default implementation checks the DisposableBean interface as well as a * specified destroy method and registered DestructionAwareBeanPostProcessors. *  * @param bean the bean instance to check * @param mbd the corresponding bean definition * @see org.springframework.beans.factory.DisposableBean * @see AbstractBeanDefinition#getDestroyMethodName() * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor */protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {    return (bean != null && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd)            || hasDestructionAwareBeanPostProcessors()));}/** * Add the given bean to the list of disposable beans in this factory, registering its * DisposableBean interface and/or the given destroy method to be called on factory * shutdown (if applicable). Only applies to singletons. *  * @param beanName the name of the bean * @param bean the bean instance * @param mbd the bean definition for the bean * @see RootBeanDefinition#isSingleton * @see RootBeanDefinition#getDependsOn * @see #registerDisposableBean * @see #registerDependentBean */protected void registerDisposableBeanIfNecessary(String beanName, Object bean,        RootBeanDefinition mbd) {    AccessControlContext acc = (System.getSecurityManager() != null            ? getAccessControlContext() : null);    if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {        if (mbd.isSingleton()) {            // Register a DisposableBean implementation that performs all destruction            // work for the given bean: DestructionAwareBeanPostProcessors,            // DisposableBean interface, custom destroy method.            registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName,                    mbd, getBeanPostProcessors(), acc));        }        else {            // A bean with a custom scope...            Scope scope = this.scopes.get(mbd.getScope());            if (scope == null) {                throw new IllegalStateException(                        "No Scope registered for scope '" + mbd.getScope() + "'");            }            scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(                    bean, beanName, mbd, getBeanPostProcessors(), acc));        }    }}// ---------------------------------------------------------------------// Abstract methods to be implemented by subclasses// ---------------------------------------------------------------------// 標記是否包含Bean定義的方法protected abstract boolean containsBeanDefinition(String beanName);// 根據Bean名返回其BeanDefinitionprotected abstract BeanDefinition getBeanDefinition(String beanName)        throws BeansException;// 根據指定的bean定義和bean名、引數,建立物件protected abstract Object createBean(String beanName, RootBeanDefinition mbd,        Object[] args) throws BeanCreationException;}

由於文章篇幅有限,IOC 面試和 AOP 相關問題將留待下一篇仔細講解。


本文首發於GitChat,未經授權不得轉載,轉載需與GitChat聯絡。

閱讀全文: http://gitbook.cn/gitchat/activity/5a03ab9fb993597ed32f8ef1

一場場看太麻煩?成為 GitChat 會員,暢享 1000+ 場 Chat !點選檢視

相關文章