天天看點

SPRING源碼分析:IOC容器

在Spring中,最基本的IOC容器接口是BeanFactory - 這個接口為具體的IOC容器的實作作了最基本的功能規定 - 不管怎麼着,作為IOC容器,這些接口你必須要滿足應用程式的最基本要求: 

public interface BeanFactory {

    //這裡是對FactoryBean的轉義定義,因為如果使用bean的名字檢索FactoryBean得到的對象是工廠生成的對象,

    //如果需要得到工廠本身,需要轉義       

    String FACTORY_BEAN_PREFIX = "&";

    //這裡根據bean的名字,在IOC容器中得到bean執行個體,這個IOC容器就是一個大的抽象工廠。

    Object getBean(String name) throws BeansException;

    //這裡根據bean的名字和Class類型來得到bean執行個體,和上面的方法不同在于它會抛出異常:如果根據名字取得的bean執行個體的Class類型和需要的不同的話。

    Object getBean(String name, Class requiredType) throws BeansException;

    //這裡提供對bean的檢索,看看是否在IOC容器有這個名字的bean

    boolean containsBean(String name);

    //這裡根據bean名字得到bean執行個體,并同時判斷這個bean是不是單件

    boolean isSingleton(String name) throws NoSuchBeanDefinitionException;

    //這裡對得到bean執行個體的Class類型

    Class getType(String name) throws NoSuchBeanDefinitionException;

    //這裡得到bean的别名,如果根據别名檢索,那麼其原名也會被檢索出來

    String[] getAliases(String name);

}

在BeanFactory裡隻對IOC容器的基本行為作了定義,根本不關心你的bean是怎樣定義怎樣加載的 - 就像我們隻關心從這個工廠裡我們得到到什麼産品對象,至于工廠是怎麼生産這些對象的,這個基本的接口不關心這些。如果要關心工廠是怎樣産生對象的,應用程式需要使用具體的IOC容器實作- 當然你可以自己根據這個BeanFactory來實作自己的IOC容器,但這個沒有必要,因為Spring已經為我們準備好了一系列工廠來讓我們使用。比如XmlBeanFactory就是針對最基礎的BeanFactory的IOC容器的實作 - 這個實作使用xml來定義IOC容器中的bean。 

Spring提供了一個BeanFactory的基本實作,XmlBeanFactory同樣的通過使用模闆模式來得到對IOC容器的抽象- AbstractBeanFactory,DefaultListableBeanFactory這些抽象類為其提供模闆服務。其中通過resource 接口來抽象bean定義資料,對Xml定義檔案的解析通過委托給XmlBeanDefinitionReader來完成。下面我們根據書上的例子,簡單的示範IOC容器的建立過程: 

    ClassPathResource res = new ClassPathResource("beans.xml");

    DefaultListableBeanFactory factory = new DefaultListableBeanFactory();

    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);

    reader.loadBeanDefinitions(res);

這些代碼示範了以下幾個步驟: 

   1. 建立IOC配置檔案的抽象資源 

   2. 建立一個BeanFactory 

   3. 把讀取配置資訊的BeanDefinitionReader,這裡是XmlBeanDefinitionReader配置給BeanFactory 

   4. 從定義好的資源位置讀入配置資訊,具體的解析過程由XmlBeanDefinitionReader來完成,這樣完成整個載入bean定義的過程。我們的IoC容器就建立起來了。在BeanFactory的源代碼中我們可以看到:

public class XmlBeanFactory extends DefaultListableBeanFactory {

    //這裡為容器定義了一個預設使用的bean定義讀取器

    private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);

    public XmlBeanFactory(Resource resource) throws BeansException {

        this(resource, null);

    }

    //在初始化函數中使用讀取器來對資源進行讀取,得到bean定義資訊。

    public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {

        super(parentBeanFactory);

        this.reader.loadBeanDefinitions(resource);

我們在後面會看到讀取器讀取資源和注冊bean定義資訊的整個過程,基本上是和上下文的處理是一樣的,從這裡我們可以看到上下文和 XmlBeanFactory這兩種IOC容器的差別,BeanFactory往往不具備對資源定義的能力,而上下文可以自己完成資源定義,從這個角度上看上下文更好用一些。 

仔細分析Spring BeanFactory的結構,我們來看看在BeanFactory基礎上擴充出的ApplicationContext - 我們最常使用的上下文。除了具備BeanFactory的全部能力,上下文為應用程式又增添了許多便利: 

    * 可以支援不同的資訊源,我們看到ApplicationContext擴充了MessageSource 

    * 通路資源 , 展現在對ResourceLoader和Resource的支援上面,這樣我們可以從不同地方得到bean定義資源 

    * 支援應用事件,繼承了接口ApplicationEventPublisher,這樣在上下文中引入了事件機制而BeanFactory是沒有的。 

ApplicationContext允許上下文嵌套 - 通過保持父上下文可以維持一個上下文體系 - 這個體系我們在以後對Web容器中的上下文環境的分析中可以清楚地看到。對于bean的查找可以在這個上下文體系中發生,首先檢查目前上下文,其次是父上下文,逐級向上,這樣為不同的Spring應用提供了一個共享的bean定義環境。這個我們在分析Web容器中的上下文環境時也能看到。 

ApplicationContext提供IoC容器的主要接口,在其體系中有許多抽象子類比如AbstractApplicationContext為具體的BeanFactory的實作,比如FileSystemXmlApplicationContext和 ClassPathXmlApplicationContext提供上下文的模闆,使得他們隻需要關心具體的資源定位問題。當應用程式代碼執行個體化 FileSystemXmlApplicationContext的時候,得到IoC容器的一種具體表現 - ApplicationContext,進而應用程式通過ApplicationContext來管理對bean的操作。 

BeanFactory 是一個接口,在實際應用中我們一般使用ApplicationContext來使用IOC容器,它們也是IOC容器展現給應用開發者的使用接口。對應用程式開發者來說,可以認為BeanFactory和ApplicationFactory在不同的使用層面上代表了SPRING提供的IOC容器服務。 

下面我們具體看看通過FileSystemXmlApplicationContext是怎樣建立起IOC容器的, 顯而易見我們可以通過new來得到IoC容器: 

   ApplicationContext = new FileSystemXmlApplicationContext(xmlPath);

調用的是它初始化代碼:

    public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)

            throws BeansException {

        super(parent);

        this.configLocations = configLocations;

        if (refresh) {

          //這裡是IoC容器的初始化過程,其初始化過程的大緻步驟由AbstractApplicationContext來定義

            refresh();

        }

refresh的模闆在AbstractApplicationContext: 

    public void refresh() throws BeansException, IllegalStateException {

        synchronized (this.startupShutdownMonitor) {

            synchronized (this.activeMonitor) {

                this.active = true;

            }

            // 這裡需要子類來協助完成資源位置定義,bean載入和向IOC容器注冊的過程

            refreshBeanFactory();

      }

這個方法包含了整個BeanFactory初始化的過程,對于特定的FileSystemXmlBeanFactory,我們看到定位資源位置由refreshBeanFactory()來實作: 

在AbstractXmlApplicationContext中定義了對資源的讀取過程,預設由XmlBeanDefinitionReader來讀取: 

    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {

        // 這裡使用XMLBeanDefinitionReader來載入bean定義資訊的XML檔案

        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

        //這裡配置reader的環境,其中ResourceLoader是我們用來定位bean定義資訊資源位置的

        ///因為上下文本身實作了ResourceLoader接口,是以可以直接把上下文作為ResourceLoader傳遞給XmlBeanDefinitionReader

        beanDefinitionReader.setResourceLoader(this);

        beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

        initBeanDefinitionReader(beanDefinitionReader);

        //這裡轉到定義好的XmlBeanDefinitionReader中對載入bean資訊進行處理

        loadBeanDefinitions(beanDefinitionReader);

轉到beanDefinitionReader中進行處理:

    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {

        Resource[] configResources = getConfigResources();

        if (configResources != null) {

            //調用XmlBeanDefinitionReader來載入bean定義資訊。

            reader.loadBeanDefinitions(configResources);

        String[] configLocations = getConfigLocations();

        if (configLocations != null) {

            reader.loadBeanDefinitions(configLocations);

而在作為其抽象父類的AbstractBeanDefinitionReader中來定義載入過程: 

    public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {

     //這裡得到目前定義的ResourceLoader,預設的我們使用DefaultResourceLoader

     ResourceLoader resourceLoader = getResourceLoader();

     .........//如果沒有找到我們需要的ResourceLoader,直接抛出異常

        if (resourceLoader instanceof ResourcePatternResolver) {

            // 這裡處理我們在定義位置時使用的各種pattern,需要ResourcePatternResolver來完成

            try {

                Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);

                int loadCount = loadBeanDefinitions(resources);

                return loadCount;

          ........

        else {

            // 這裡通過ResourceLoader來完成位置定位

            Resource resource = resourceLoader.getResource(location);

            // 這裡已經把一個位置定義轉化為Resource接口,可以供XmlBeanDefinitionReader來使用了

            int loadCount = loadBeanDefinitions(resource);

            return loadCount;

當我們通過ResourceLoader來載入資源,别忘了了我們的GenericApplicationContext也實作了ResourceLoader接口: 

    public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {

        public Resource getResource(String location) {

            //這裡調用目前的loader也就是DefaultResourceLoader來完成載入

            if (this.resourceLoader != null) {

                return this.resourceLoader.getResource(location);

            return super.getResource(location);

    .......

而我們的FileSystemXmlApplicationContext就是一個DefaultResourceLoader - GenericApplicationContext()通過DefaultResourceLoader: 

    public Resource getResource(String location) {

        //如果是類路徑的方式,那需要使用ClassPathResource來得到bean檔案的資源對象

        if (location.startsWith(CLASSPATH_URL_PREFIX)) {

            return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());

                // 如果是URL方式,使用UrlResource作為bean檔案的資源對象

                URL url = new URL(location);

                return new UrlResource(url);

            catch (MalformedURLException ex) {

                // 如果都不是,那我們隻能委托給子類由子類來決定使用什麼樣的資源對象了

                return getResourceByPath(location);

我們的FileSystemXmlApplicationContext本身就是是DefaultResourceLoader的實作類,他實作了以下的接口:

    protected Resource getResourceByPath(String path) {

        if (path != null && path.startsWith("/")) {

            path = path.substring(1);

        //這裡使用檔案系統資源對象來定義bean檔案

        return new FileSystemResource(path);

這樣代碼就回到了FileSystemXmlApplicationContext中來,他提供了FileSystemResource來完成從檔案系統得到配置檔案的資源定義。這樣,就可以從檔案系統路徑上對IOC配置檔案進行加載 - 當然我們可以按照這個邏輯從任何地方加載,在Spring中我們看到它提供的各種資源抽象,比如ClassPathResource, URLResource,FileSystemResource等來供我們使用。上面我們看到的是定位Resource的一個過程,而這隻是加載過程的一部分 - 我們回到AbstractBeanDefinitionReaderz中的loadDefinitions(resource)來看看得到代表bean檔案的資源定義以後的載入過程,預設的我們使用XmlBeanDefinitionReader:

    public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {

        .......

        try {

            //這裡通過Resource得到InputStream的IO流

            InputStream inputStream = encodedResource.getResource().getInputStream();

                //從InputStream中得到XML的解析源

                InputSource inputSource = new InputSource(inputStream);

                if (encodedResource.getEncoding() != null) {

                    inputSource.setEncoding(encodedResource.getEncoding());

                }

                //這裡是具體的解析和注冊過程

                return doLoadBeanDefinitions(inputSource, encodedResource.getResource());

            finally {

                //關閉從Resource中得到的IO流

                inputStream.close();

           .........

    protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)

            throws BeanDefinitionStoreException {

            int validationMode = getValidationModeForResource(resource);

            //通過解析得到DOM,然後完成bean在IOC容器中的注冊

            Document doc = this.documentLoader.loadDocument(

                    inputSource, this.entityResolver, this.errorHandler, validationMode, this.namespaceAware);

            return registerBeanDefinitions(doc, resource);

我們看到先把定義檔案解析為DOM對象,然後進行具體的注冊過程:

    public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {

        // 這裡定義解析器,使用XmlBeanDefinitionParser來解析xml方式的bean定義檔案 - 現在的版本不用這個解析器了,使用的是XmlBeanDefinitionReader

        if (this.parserClass != null) {

            XmlBeanDefinitionParser parser =

                    (XmlBeanDefinitionParser) BeanUtils.instantiateClass(this.parserClass);

            return parser.registerBeanDefinitions(this, doc, resource);

        // 具體的注冊過程,首先得到XmlBeanDefinitionReader,來處理xml的bean定義檔案

        BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();

        int countBefore = getBeanFactory().getBeanDefinitionCount();

        documentReader.registerBeanDefinitions(doc, createReaderContext(resource));

        return getBeanFactory().getBeanDefinitionCount() - countBefore;

具體的在BeanDefinitionDocumentReader中完成對,下面是一個簡要的注冊過程來完成bean定義檔案的解析和IOC容器中bean的初始化 

    public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {

        this.readerContext = readerContext;

        logger.debug("Loading bean definitions");

        Element root = doc.getDocumentElement();

        BeanDefinitionParserDelegate delegate = createHelper(readerContext, root);

        preProcessXml(root);

        parseBeanDefinitions(root, delegate);

        postProcessXml(root);

    protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {

        if (delegate.isDefaultNamespace(root.getNamespaceURI())) {

            //這裡得到xml檔案的子節點,比如各個bean節點         

            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;

                    String namespaceUri = ele.getNamespaceURI();

                    if (delegate.isDefaultNamespace(namespaceUri)) {

                        //這裡是解析過程的調用,對預設的元素進行分析比如bean元素

                        parseDefaultElement(ele, delegate);

                    }

                    else {

                        delegate.parseCustomElement(ele);

        } else {

            delegate.parseCustomElement(root);

    private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {

        //這裡對元素Import進行處理

        if (DomUtils.nodeNameEquals(ele, IMPORT_ELEMENT)) {

            importBeanDefinitionResource(ele);

        else if (DomUtils.nodeNameEquals(ele, ALIAS_ELEMENT)) {

            String name = ele.getAttribute(NAME_ATTRIBUTE);

            String alias = ele.getAttribute(ALIAS_ATTRIBUTE);

            getReaderContext().getReader().getBeanFactory().registerAlias(name, alias);

            getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));

        //這裡對我們最熟悉的bean元素進行處理

        else if (DomUtils.nodeNameEquals(ele, BEAN_ELEMENT)) {

            //委托給BeanDefinitionParserDelegate來完成對bean元素的處理,這個類包含了具體的bean解析的過程。

            // 把解析bean檔案得到的資訊放到BeanDefinition裡,他是bean資訊的主要載體,也是IOC容器的管理對象。

            BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);

            if (bdHolder != null) {

                bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);

                // 這裡是向IOC容器注冊,實際上是放到IOC容器的一個map裡

                BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());

                // 這裡向IOC容器發送事件,表示解析和注冊完成。

                getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));

我們看到在parseBeanDefinition中對具體bean元素的解析式交給BeanDefinitionParserDelegate來完成的,下面我們看看解析完的bean是怎樣在IOC容器中注冊的:在BeanDefinitionReaderUtils調用的是: 

    public static void registerBeanDefinition(

            BeanDefinitionHolder bdHolder, BeanDefinitionRegistry beanFactory) throws BeansException {

        // 這裡得到需要注冊bean的名字;

        String beanName = bdHolder.getBeanName();

        //這是調用IOC來注冊的bean的過程,需要得到BeanDefinition

        beanFactory.registerBeanDefinition(beanName, bdHolder.getBeanDefinition());

        // 别名也是可以通過IOC容器和bean聯系起來的進行注冊

        String[] aliases = bdHolder.getAliases();

        if (aliases != null) {

            for (int i = 0; i < aliases.length; i++) {

                beanFactory.registerAlias(beanName, aliases[i]);

我們看看XmlBeanFactory中的注冊實作:

    //---------------------------------------------------------------------

    // 這裡是IOC容器對BeanDefinitionRegistry接口的實作

    //---------------------------------------------------------------------

    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)

        .....//這裡省略了對BeanDefinition的驗證過程

        //先看看在容器裡是不是已經有了同名的bean,如果有抛出異常。

        Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);

        if (oldBeanDefinition != null) {

            if (!this.allowBeanDefinitionOverriding) {

            ...........

            //把bean的名字加到IOC容器中去

            this.beanDefinitionNames.add(beanName);

        //這裡把bean的名字和Bean定義聯系起來放到一個HashMap中去,IOC容器通過這個Map來維護容器裡的Bean定義資訊。

        this.beanDefinitionMap.put(beanName, beanDefinition);

        removeSingleton(beanName);