彻底搞懂Bean加载

本文转自:Java知音

0. Bean 加载原理

加载过程: 通过 ResourceLoader和其子类 DefaultResourceLoader完成资源文件位置定位,实现从类路径,文件系统,url等方式定位功能,完成定位后得到 Resource对象,再交给 BeanDefinitionReader,它再委托给 BeanDefinitionParserDelegate完成bean的解析并得到 BeanDefinition对象,然后通过 registerBeanDefinition方法进行注册,IOC容器内ibu维护了一个HashMap来保存该 BeanDefinition对象,Spring中的 BeanDefinition其实就是我们用的 JavaBean

什么是BeanDefinition对象

BeanDefinition是一个接口,描述了一个bean实例,它具有属性值,构造函数参数值以及具体实现提供的更多信息。

注重理解加载过程

在开始之前需要认真阅读和理解这个过程,有了这个过程,阅读源码难度就小了一半。

大多源码都进行了注释,有的是官方英文注释。中文是主线(本文也主要也是过一遍主线),想要面面俱到需要自己再去摸索。

1. bean.xml

一个普通的bean配置文件,这里我要强调的是它里面的格式,因为解析标签的时候会用到。它有 <beans> <bean> <import> <alias>等标签,下文会对他们进行解析并翻译成BeanDefinition对象。

 
  1. <beans>

  2.  

  3.  <!-- this definition could be inside one beanRefFactory.xml file -->

  4.  <bean id="a.qualified.name.of.some.sort"

  5.      class="org.springframework.context.support.ClassPathXmlApplicationContext">

  6.    <property name="configLocation" value="org/springframework/web/context/beans1.xml"/>

  7.  </bean>

  8.  

  9.  <!-- while the following two could be inside another, also on the classpath,

  10.    perhaps coming from another component jar -->

  11.  <bean id="another.qualified.name"

  12.      class="org.springframework.context.support.ClassPathXmlApplicationContext">

  13.    <property name="configLocation" value="org/springframework/web/context/beans1.xml"/>

  14.    <property name="parent" ref="a.qualified.name.of.some.sort"/>

  15.  </bean>

  16.  

  17.  <alias name="another.qualified.name" alias="a.qualified.name.which.is.an.alias"/>

  18.  

  19. </beans>

2. ResourceLoader.java

加载资源的策略接口(策略模式)。 DefaultResourceLoader is a standalone implementation that is usable outside an ApplicationContext, also used by ResourceEditor

An ApplicationContext is required to provide this functionality, plus extended ResourcePatternResolver support.

 
  1. public interface ResourceLoader {

  2.  

  3.    /** Pseudo URL prefix for loading from the class path: "classpath:". */

  4.    String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;

  5.  

  6.        // 返回一个Resource 对象 (明确配置文件位置的对象)

  7.    Resource getResource(String location);

  8.  

  9.        // 返回ResourceLoader的ClassLoader

  10.    @Nullable

  11.    ClassLoader getClassLoader();

  12. }

然后我们看看 DefaultResourceLoader对于 getResource()方法的实现。

 
  1.    public Resource getResource(String location) {

  2.        Assert.notNull(location, "Location must not be null");

  3.  

  4.        for (ProtocolResolver protocolResolver : this.protocolResolvers) {

  5.            Resource resource = protocolResolver.resolve(location, this);

  6.            if (resource != null) {

  7.                return resource;

  8.            }

  9.        }

  10.               // 如果location 以 / 开头

  11.        if (location.startsWith("/")) {

  12.            return getResourceByPath(location);

  13.        }

  14.                // 如果location 以classpath: 开头

  15.        else if (location.startsWith(CLASSPATH_URL_PREFIX)) {

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

  17.        }

  18.        else {

  19.            try {

  20.                // Try to parse the location as a URL...

  21.                URL url = new URL(location);

  22.                return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));

  23.            }

  24.            catch (MalformedURLException ex) {

  25.                // No URL -> resolve as resource path.

  26.                return getResourceByPath(location);

  27.            }

  28.        }

  29.    }

可以看到,它判断了三种情况: / classpath: url格式匹配, 然后调用相对应的处理方法,我只分析 classpath:,因为这是最常用的。所以看一看 ClassPathResource实现:

 
  1.    public ClassPathResource(String path, @Nullable ClassLoader classLoader) {

  2.        Assert.notNull(path, "Path must not be null");

  3.        String pathToUse = StringUtils.cleanPath(path);

  4.        if (pathToUse.startsWith("/")) {

  5.            pathToUse = pathToUse.substring(1);

  6.        }

  7.        this.path = pathToUse;

  8.        this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());

  9.    }

看了上面的代码,意味着你配置静态资源文件路径的时候,不用纠结 classpath:后面用不用写 /,因为如果写了它会给你过滤掉。

那url如何定位的呢?

跟踪getResourceByPath(location)方法:

 
  1.    @Override

  2.    protected Resource getResourceByPath(String path) {

  3.        if (path.startsWith("/")) {

  4.            path = path.substring(1);

  5.        }

  6.        // 这里使用文件系统资源对象来定义bean文件

  7.        return new FileSystemResource(path);

  8.    }

好了,很明显...跑偏了,因为我们想要的是xml文件及路径的解析,不过还好,换汤不换药。下文中会涉及到。

触发bean加载

回到正题,我们在使用spring手动加载bean.xml的时候,用到:

 
  1. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");

那就从 ClassPathXmlApplicationContext类开始深入:

3. ClassPathXmlApplicationContext.java

这个类里面只有构造方法(多个)和一个getConfigResources()方法,构造方法最终都统一打到下面这个构造方法中(适配器模式):

 
  1.    public ClassPathXmlApplicationContext(

  2.            String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)

  3.            throws BeansException {

  4.    // 动态的确定用哪个加载器去加载 配置文件

  5.        1.super(parent);

  6.    // 告诉读取器 配置文件在哪里, 定位加载配置文件

  7.        2.setConfigLocations(configLocations);

  8.    // 刷新

  9.        if (refresh) {

  10.            // 在创建IOC容器前,如果容器已经存在,则需要把已有的容器摧毁和关闭,以保证refresh

  11.            //之后使用的是新的IOC容器

  12.            3.refresh();

  13.        }

  14.    }

注意: 这个类非常关键,我认为它定义了一个 xml加载 bean的一个 LifeCycle:

  • super() 方法完成类加载器的指定。

  • setConfigLocations(configLocations);方法对配置文件进行定位和解析,拿到Resource对象。

  • refresh();方法对标签进行解析拿到BeanDefition对象,在通过校验后将其注册到IOC容器。(主要研究该方法)

我标记的1. 2. 3. 对应后面的方法x, 方便阅读。

先深入了解下 setConfigLocations(configLocations);方法:

方法2. setConfigLocations(configLocations)

 
  1.    // 解析Bean定义资源文件的路径,处理多个资源文件字符串数组

  2.    public void setConfigLocations(@Nullable String... locations) {

  3.        if (locations != null) {

  4.            Assert.noNullElements(locations, "Config locations must not be null");

  5.            this.configLocations = new String[locations.length];

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

  7.                // resolvePath 为同一个类中将字符串解析为路径的方法

  8.                this.configLocations[i] = resolvePath(locations[i]).trim();

  9.            }

  10.        }

  11.        else {

  12.            this.configLocations = null;

  13.        }

  14.    }

然后我们继续上面看 ClassPathXmlApplicationContext的 refresh()方法:

方法3. refresh()

 
  1.    public void refresh() throws BeansException, IllegalStateException {

  2.        synchronized (this.startupShutdownMonitor) {

  3.            // 为refresh 准备上下文

  4.            prepareRefresh();

  5.  

  6.            // 通知子类去刷新 Bean工厂

  7.            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

  8.  

  9.            // 用该上下文来 准备bean工厂

  10.            prepareBeanFactory(beanFactory);

  11.  

  12.            try {

  13.                // Allows post-processing of the bean factory in context subclasses.

  14.                postProcessBeanFactory(beanFactory);

  15.  

  16.                // Invoke factory processors registered as beans in the context.

  17.                invokeBeanFactoryPostProcessors(beanFactory);

  18.  

  19.                // Register bean processors that intercept bean creation.

  20.                registerBeanPostProcessors(beanFactory);

  21.  

  22.                // Initialize message source for this context.

  23.                initMessageSource();

  24.  

  25.                // Initialize event multicaster for this context.

  26.                initApplicationEventMulticaster();

  27.  

  28.                // Initialize other special beans in specific context subclasses.

  29.                onRefresh();

  30.  

  31.                // Check for listener beans and register them.

  32.                registerListeners();

  33.  

  34.                // Instantiate all remaining (non-lazy-init) singletons.

  35.                finishBeanFactoryInitialization(beanFactory);

  36.  

  37.                // Last step: publish corresponding event.

  38.                finishRefresh();

  39.            }

  40.  

  41.            catch (BeansException ex) {

  42.                if (logger.isWarnEnabled()) {

  43.                    logger.warn("Exception encountered during context initialization - " +

  44.                            "cancelling refresh attempt: " + ex);

  45.                }

  46.  

  47.                // Destroy already created singletons to avoid dangling resources.

  48.                destroyBeans();

  49.  

  50.                // Reset 'active' flag.

  51.                cancelRefresh(ex);

  52.  

  53.                // Propagate exception to caller.

  54.                throw ex;

  55.            }

  56.  

  57.            finally {

  58.                // Reset common introspection caches in Spring's core, since we

  59.                // might not ever need metadata for singleton beans anymore...

  60.                resetCommonCaches();

  61.            }

  62.        }

  63.    }

注:下面的方法全都是围绕 refresh()里深入阅读,该方法套的很深,下面的阅读可能会引起不适。

然后看看 refresh()方法中的 obtainFreshBeanFactory()方法:

方法3.1 obtainFreshBeanFactory()

 
  1.    // 调用--刷新bean工厂

  2.    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {

  3.        // 委派模式:父类定义了refreshBeanFactory方法,具体实现调用子类容器

  4.        refreshBeanFactory();

  5.        return getBeanFactory();

  6.    }

然后看 obtainFreshBeanFactory()的 refreshBeanFactory()方法

方法3.1.1 refreshBeanFactory()

 
  1.       // 刷新bean工厂

  2.    protected final void refreshBeanFactory() throws BeansException {

  3.        // 如果存在容器,就先销毁并关闭

  4.        if (hasBeanFactory()) {

  5.            destroyBeans();

  6.            closeBeanFactory();

  7.        }

  8.        try {

  9.            // 创建IOC容器

  10.            DefaultListableBeanFactory beanFactory = createBeanFactory();

  11.            beanFactory.setSerializationId(getId());

  12.            // 对容器进行初始化

  13.            customizeBeanFactory(beanFactory);

  14.            // 调用载入Bean定义的方法,(使用了委派模式)

  15.            loadBeanDefinitions(beanFactory);

  16.            synchronized (this.beanFactoryMonitor) {

  17.                this.beanFactory = beanFactory;

  18.            }

  19.        }

  20.        catch (IOException ex) {

  21.            throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);

  22.        }

  23.    }

然后再跟进 refreshBeanFactory()的 loadBeanDefinitions()方法:

方法3.1.1.1 loadBeanDefinitions()

通过 XmlBeanDefinitionReader 加载 BeanDefinition

 
  1.    // 通过 XmlBeanDefinitionReader 加载 BeanDefinition

  2.    @Override

  3.    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {

  4.        // Create a new XmlBeanDefinitionReader for the given BeanFactory.

  5.        // 为beanFactory 创建一个新的 XmlBeanDefinitionReader

  6.        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

  7.  

  8.        // Configure the bean definition reader with this context's

  9.        // resource loading environment.

  10.        beanDefinitionReader.setEnvironment(this.getEnvironment());

  11.        // 为 Bean读取器设置Spring资源加载器 (因为祖父类是ResourceLoader的子类,所以也是ResourceLoader)

  12.        beanDefinitionReader.setResourceLoader(this);

  13.        //  为 Bean读取器设置SAX xml解析器DOM4J

  14.        beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

  15.  

  16.        // Allow a subclass to provide custom initialization of the reader,

  17.        // then proceed with actually loading the bean definitions.

  18.        // 初始化 BeanDefinition读取器

  19.        initBeanDefinitionReader(beanDefinitionReader);

  20.        // 真正加载 bean定义

  21.        loadBeanDefinitions(beanDefinitionReader);

  22.    }

再跟进 loadBeanDefinitions(DefaultListableBeanFactorybeanFactory)方法中的 loadBeanDefinitions(XmlBeanDefinitionReaderreader)方法:

方法3.1.1.1.1 loadBeanDefinitions()

XMLBean读取器加载BeanDefinition 资源

 
  1.    // XMLBean读取器加载Bean 定义资源

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

  3.        // 获取Bean定义资源的定位

  4.        Resource[] configResources = getConfigResources();

  5.        if (configResources != null) {

  6.            // XMLBean读取器调用其父类 AbstractBeanDefinitionReader 读取定位的Bean定义资源

  7.            reader.loadBeanDefinitions(configResources);

  8.        }

  9.        // 如果子类中获取的bean定义资源定位为空,

  10.        // 则获取 FileSystemXmlApplicationContext构造方法中 setConfigLocations 方法设置的资源

  11.        String[] configLocations = getConfigLocations();

  12.        if (configLocations != null) {

  13.            // XMLBean读取器调用其父类 AbstractBeanDefinitionReader 读取定位的Bean定义资源

  14.            reader.loadBeanDefinitions(configLocations);

  15.        }

  16.    }

 

 
  1.    @Override

  2.    public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {

  3.        Assert.notNull(resources, "Resource array must not be null");

  4.        int count = 0;

  5.        //

  6.        for (Resource resource : resources) {

  7.            count += loadBeanDefinitions(resource);

  8.        }

  9.        return count;

  10.    }

再跟下去 loadBeanDefinitions(): 这只是一个抽象方法,找到 XmlBeanDefinitionReader子类的实现:

 
  1.    @Override

  2.    public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {

  3.        return loadBeanDefinitions(new EncodedResource(resource));

  4.    }

再深入 loadBeanDefinitions:

通过明确的xml文件加载bean

 
  1.    // 通过明确的xml文件加载bean

  2.    public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {

  3.        Assert.notNull(encodedResource, "EncodedResource must not be null");

  4.        if (logger.isTraceEnabled()) {

  5.            logger.trace("Loading XML bean definitions from " + encodedResource);

  6.        }

  7.  

  8.        Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();

  9.        if (currentResources == null) {

  10.            currentResources = new HashSet<>(4);

  11.            this.resourcesCurrentlyBeingLoaded.set(currentResources);

  12.        }

  13.        if (!currentResources.add(encodedResource)) {

  14.            throw new BeanDefinitionStoreException(

  15.                    "Detected cyclic loading of " + encodedResource + " - check your import definitions!");

  16.        }

  17.        try {

  18.            // 将资源文件转为InputStream的IO流

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

  20.            try {

  21.                // 从流中获取 xml解析资源

  22.                InputSource inputSource = new InputSource(inputStream);

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

  24.                    // 设置编码

  25.                    inputSource.setEncoding(encodedResource.getEncoding());

  26.                }

  27.                // 具体的读取过程

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

  29.            }

  30.            finally {

  31.                inputStream.close();

  32.            }

  33.        }

  34.        catch (IOException ex) {

  35.            throw new BeanDefinitionStoreException(

  36.                    "IOException parsing XML document from " + encodedResource.getResource(), ex);

  37.        }

  38.        finally {

  39.            currentResources.remove(encodedResource);

  40.            if (currentResources.isEmpty()) {

  41.                this.resourcesCurrentlyBeingLoaded.remove();

  42.            }

  43.        }

  44.    }

再深入到 doLoadBeanDefinitions():

真正开始加载 BeanDefinitions

 
  1.    protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)

  2.            throws BeanDefinitionStoreException {

  3.  

  4.        try {

  5.            // 将xml 文件转换为DOM对象

  6.            Document doc = doLoadDocument(inputSource, resource);

  7.            // 对bean定义解析的过程,该过程会用到 Spring的bean配置规则

  8.            int count = registerBeanDefinitions(doc, resource);

  9.            if (logger.isDebugEnabled()) {

  10.                logger.debug("Loaded " + count + " bean definitions from " + resource);

  11.            }

  12.            return count;

  13.        }

  14.        ...  ...  ..

  15. }

doLoadDocument()方法将流进行解析,返回一个Document对象: returnbuilder.parse(inputSource);为了避免扰乱思路,这里的深入自己去完成。

还需要再深入到: registerBeanDefinitions()

注册 BeanDefinitions

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

  2.        BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();

  3.        // 得到容器中注册的bean数量

  4.        int countBefore = getRegistry().getBeanDefinitionCount();

  5.        // 解析过程入口,这里使用了委派模式

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

  7.        // 统计解析的bean数量

  8.        return getRegistry().getBeanDefinitionCount() - countBefore;

  9.    }

再深入 registerBeanDefinitions()方法(该方法是委派模式的结果):

 
  1.    @Override

  2.    public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {

  3.        // 获得XML描述符

  4.        this.readerContext = readerContext;

  5.        doRegisterBeanDefinitions(doc.getDocumentElement());

  6.    }

再深入 doRegisterBeanDefinitions(doc.getDocumentElement());

真正开始注册 BeanDefinitions :

 
  1. protected void doRegisterBeanDefinitions(Element root) {

  2.        // Any nested <beans> elements will cause recursion in this method. In

  3.        // order to propagate and preserve <beans> default-* attributes correctly,

  4.        // keep track of the current (parent) delegate, which may be null. Create

  5.        // the new (child) delegate with a reference to the parent for fallback purposes,

  6.        // then ultimately reset this.delegate back to its original (parent) reference.

  7.        // this behavior emulates a stack of delegates without actually necessitating one.

  8.        BeanDefinitionParserDelegate parent = this.delegate;

  9.        this.delegate = createDelegate(getReaderContext(), root, parent);

  10.  

  11.        if (this.delegate.isDefaultNamespace(root)) {

  12.            String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);

  13.            if (StringUtils.hasText(profileSpec)) {

  14.                String[] specifiedProfiles = StringUtils.tokenizeToStringArray(

  15.                        profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);

  16.                // We cannot use Profiles.of(...) since profile expressions are not supported

  17.                // in XML config. See SPR-12458 for details.

  18.                if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {

  19.                    if (logger.isDebugEnabled()) {

  20.                        logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +

  21.                                "] not matching: " + getReaderContext().getResource());

  22.                    }

  23.                    return;

  24.                }

  25.            }

  26.        }

  27.  

  28.        // 在bean解析定义之前,进行自定义解析,看是否是用户自定义标签

  29.        preProcessXml(root);

  30.        // 开始进行解析bean定义的document对象

  31.        parseBeanDefinitions(root, this.delegate);

  32.        // 解析bean定义之后,进行自定义的解析,增加解析过程的可扩展性

  33.        postProcessXml(root);

  34.  

  35.        this.delegate = parent;

  36.    }

接下来看 parseBeanDefinitions(root,this.delegate);:

document的根元素开始进行解析翻译成BeanDefinitions

 
  1.    // 从document的根元素开始进行解析翻译成BeanDefinitions

  2.    protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {

  3.        // bean定义的document对象使用了spring默认的xml命名空间

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

  5.            // 获取bean定义的document对象根元素的所有字节点

  6.            NodeList nl = root.getChildNodes();

  7.            for (int i = 0; i < nl.getLength(); i++) {

  8.                Node node = nl.item(i);

  9.                // 获得document节点是xml元素节点

  10.                if (node instanceof Element) {

  11.                    Element ele = (Element) node;

  12.                    // bean定义的document的元素节点使用的是spring默认的xml命名空间

  13.                    if (delegate.isDefaultNamespace(ele)) {

  14.                        // 使用spring的bean规则解析元素 节点

  15.                        parseDefaultElement(ele, delegate);

  16.                    }

  17.                    else {

  18.                        // 没有使用spring默认的xml命名空间,则使用用户自定义的解析规则解析元素节点

  19.                        delegate.parseCustomElement(ele);

  20.                    }

  21.                }

  22.            }

  23.        }

  24.        else {

  25.            delegate.parseCustomElement(root);

  26.        }

  27.    }

  28.  

  29.    private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {

  30.        // 解析 <import> 标签元素,并进行导入解析

  31.        if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {

  32.            importBeanDefinitionResource(ele);

  33.        }

  34.        // alias

  35.        else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {

  36.            processAliasRegistration(ele);

  37.        }

  38.        // bean

  39.        else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {

  40.            processBeanDefinition(ele, delegate);

  41.        }

  42.        // beans

  43.        else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {

  44.            // recurse

  45.            doRegisterBeanDefinitions(ele);

  46.        }

  47.    }

importBeanDefinitionResource(ele);``processAliasRegistration(ele);``processBeanDefinition(ele,delegate);这三个方法里分别展示了标签解析的详细过程。 这下看到了,它其实使用DOM4J来解析 import bean alias等标签,然后递归标签内部直到拿到所有属性并封装到BeanDefition对象中。比如说 processBeanDefinition方法:

给我一个element 解析成 BeanDefinition

 
  1.    // 给我一个element 解析成 BeanDefinition

  2.    protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {

  3.        // 真正解析过程

  4.        BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);

  5.        if (bdHolder != null) {

  6.            bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);

  7.            try {

  8.                // Register the final decorated instance.

  9.                // 注册: 将db注册到ioc,委托模式

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

  11.            }

  12.            catch (BeanDefinitionStoreException ex) {

  13.                getReaderContext().error("Failed to register bean definition with name '" +

  14.                        bdHolder.getBeanName() + "'", ele, ex);

  15.            }

  16.            // Send registration event.

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

  18.        }

  19.    }

继续深入 registerBeanDefinition():

注册BeanDefinitions 到 bean 工厂

 
  1.    // 注册BeanDefinitions 到 bean 工厂

  2.    // definitionHolder : bean定义,包含了 name和aliases

  3.    // registry: 注册到的bean工厂

  4.    public static void registerBeanDefinition(

  5.            BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)

  6.            throws BeanDefinitionStoreException {

  7.  

  8.        // Register bean definition under primary name.

  9.        String beanName = definitionHolder.getBeanName();

  10.        // 真正注册

  11.        registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

  12.  

  13.        // Register aliases for bean name, if any.

  14.        String[] aliases = definitionHolder.getAliases();

  15.        if (aliases != null) {

  16.            for (String alias : aliases) {

  17.                registry.registerAlias(beanName, alias);

  18.            }

  19.        }

  20.    }

再深入 registry.registerBeanDefinition(beanName,definitionHolder.getBeanDefinition());

注册BeanDefinitions 到IOC容器

注意:该方法所在类是接口,我们查看的是 DefaultListableBeanFactory.java所实现的该方法。

 
  1.    // 实现BeanDefinitionRegistry接口,注册BeanDefinitions

  2.    @Override

  3.    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)

  4.            throws BeanDefinitionStoreException {

  5.  

  6.        Assert.hasText(beanName, "Bean name must not be empty");

  7.        Assert.notNull(beanDefinition, "BeanDefinition must not be null");

  8.  

  9.        // 校验是否是 AbstractBeanDefinition)

  10.        if (beanDefinition instanceof AbstractBeanDefinition) {

  11.            try {

  12.                // 标记 beanDefinition 生效

  13.                ((AbstractBeanDefinition) beanDefinition).validate();

  14.            }

  15.            catch (BeanDefinitionValidationException ex) {

  16.                throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,

  17.                        "Validation of bean definition failed", ex);

  18.            }

  19.        }

  20.  

  21.        // 判断beanDefinitionMap 里是否已经有这个bean

  22.        BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);

  23.        //如果没有这个bean

  24.        if (existingDefinition != null) {

  25.            //如果不允许bd 覆盖已注册的bean, 就抛出异常

  26.            if (!isAllowBeanDefinitionOverriding()) {

  27.                throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);

  28.            }

  29.            // 如果允许覆盖, 则同名的bean, 注册的覆盖先注册的

  30.            else if (existingDefinition.getRole() < beanDefinition.getRole()) {

  31.                // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE

  32.                if (logger.isInfoEnabled()) {

  33.                    logger.info("Overriding user-defined bean definition for bean '" + beanName +

  34.                            "' with a framework-generated bean definition: replacing [" +

  35.                            existingDefinition + "] with [" + beanDefinition + "]");

  36.                }

  37.            }

  38.            else if (!beanDefinition.equals(existingDefinition)) {

  39.                if (logger.isDebugEnabled()) {

  40.                    logger.debug("Overriding bean definition for bean '" + beanName +

  41.                            "' with a different definition: replacing [" + existingDefinition +

  42.                            "] with [" + beanDefinition + "]");

  43.                }

  44.            }

  45.            else {

  46.                if (logger.isTraceEnabled()) {

  47.                    logger.trace("Overriding bean definition for bean '" + beanName +

  48.                            "' with an equivalent definition: replacing [" + existingDefinition +

  49.                            "] with [" + beanDefinition + "]");

  50.                }

  51.            }

  52.            // 注册到容器,beanDefinitionMap 就是个容器

  53.            this.beanDefinitionMap.put(beanName, beanDefinition);

  54.        }

  55.        else {

  56.            if (hasBeanCreationStarted()) {

  57.                // Cannot modify startup-time collection elements anymore (for stable iteration)

  58.                synchronized (this.beanDefinitionMap) {

  59.                    this.beanDefinitionMap.put(beanName, beanDefinition);

  60.                    List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);

  61.                    updatedDefinitions.addAll(this.beanDefinitionNames);

  62.                    updatedDefinitions.add(beanName);

  63.                    this.beanDefinitionNames = updatedDefinitions;

  64.                    if (this.manualSingletonNames.contains(beanName)) {

  65.                        Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);

  66.                        updatedSingletons.remove(beanName);

  67.                        this.manualSingletonNames = updatedSingletons;

  68.                    }

  69.                }

  70.            }

  71.            else {

  72.                // Still in startup registration phase

  73.                this.beanDefinitionMap.put(beanName, beanDefinition);

  74.                this.beanDefinitionNames.add(beanName);

  75.                this.manualSingletonNames.remove(beanName);

  76.            }

  77.            this.frozenBeanDefinitionNames = null;

  78.        }

  79.  

  80.        if (existingDefinition != null || containsSingleton(beanName)) {

  81.            resetBeanDefinition(beanName);

  82.        }

  83.    }

这个方法中对所需要加载的bean进行校验,没有问题的话就 put到 beanDefinitionMap中, beanDefinitionMap其实就是IOC.这样我们的Bean就被加载到IOC容器中了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值