Spring 解析注册BeanDefinition这一篇就Over

一、简介:

        学习过Spring框架的人一定都会听过Spring的IoC(控制反转) 、DI(依赖注入)这两个概念,对于初学Spring的人来说,总觉得IoC 、DI这两个概念是模糊不清的,最近学习了Spring源码,有了新的理解,今天带大家谈谈我对Spring Ioc的理解。

        如图:

        实际上我们将我们的类全部注入到IOC这个容器中,类的创建销毁等全部交由IOC处理。Spring核心思想就是IOC思想。        

        拿掉IOC容器可以看出来,各个类之间没有任何关系,因为我们对类的使用都是通过容器去获取的,因此起到了解耦的作用。


二、简述Spring整体处理流程

        接下来先讲解Spring一个大概的流程处理过程。

读取XML - 解析XML封装成DOC对象 - DOC对象转换成Spring beanDefinition对象 -  转换成metaData对象 -  获取metaData对象开始创建bean

         大家一定要多注意beanDefinition、metaData 这些类,他们在Spring源码中出现的次数非常多。

beanDefinition:是解析XML封装的一些数据。

metaData:是对类元数据的封装。

三、BeanDefinition注册过程

        下面从源码上给大家跟一下BeanDefinition的注册过程。建议大家也都根据我的注释,也从源码上一个一个的跟一下。

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


    super(parent);


    //创建解析器,解析configLocations
    setConfigLocations(configLocations);
    if (refresh) {
            // 核心方法
      refresh();
    }
  }
// AbstractApplicationContext.java
/*
   *  该方法是spring容器初始化的核心方法。是spring容器初始化的核心流程,是一个典型的父类模板设计模式的运用
   *  根据不同的上下文对象,会调到不同的上下文对象子类方法中
   *
   *  核心上下文子类有:
   *  ClassPathXmlApplicationContext
   *  FileSystemXmlApplicationContext
   *  AnnotationConfigApplicationContext
   *  EmbeddedWebApplicationContext(springboot) 里面会用到钩子方法启动内嵌tomcat
   * */
  @Override
  public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
      //为容器初始化做准备
      // Prepare this context for refreshing.
      prepareRefresh();


      /*
        非常重要
        1、创建BeanFactory对象
      * 2、xml解析
      *   传统标签解析:bean、import等
      *   自定义标签解析 如:<context:component-scan base-package="com.xiangxue.jack"/>
      *   自定义标签解析流程:
      *     a、根据当前解析标签的头信息找到对应的namespaceUri
      *     b、加载spring所以jar中的spring.handlers文件。并建立映射关系
      *     c、根据namespaceUri从映射关系中找到对应的实现了NamespaceHandler接口的类
      *     d、调用类的init方法,init方法是注册了各种自定义标签的解析类
      *     e、根据namespaceUri找到对应的解析类,然后调用paser方法完成标签解析
      *
      * 3、把解析出来的xml标签封装成BeanDefinition对象
      * */
      // Tell the subclass to refresh the internal bean factory.
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();


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


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


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


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


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


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


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


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


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


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


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


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


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


        // Propagate exception to caller.
        throw ex;
      }


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


@Override
  protected final void refreshBeanFactory() throws BeansException {


    //如果BeanFactory不为空,则清除BeanFactory和里面的实例
    if (hasBeanFactory()) {
      destroyBeans();
      closeBeanFactory();
    }
    try {
      //创建DefaultListableBeanFactory
      DefaultListableBeanFactory beanFactory = createBeanFactory();
      beanFactory.setSerializationId(getId());


      //设置是否可以循环依赖 allowCircularReferences
      //是否允许使用相同名称重新注册不同的bean实现.
      customizeBeanFactory(beanFactory);


      //解析xml,并把xml中的标签封装成BeanDefinition对象
      loadBeanDefinitions(beanFactory);
      synchronized (this.beanFactoryMonitor) {
        this.beanFactory = beanFactory;
      }
    }
    catch (IOException ex) {
      throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
    }
  }
// AbstractXmlApplicationContext.java
@Override
  protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
    // Create a new XmlBeanDefinitionReader for the given BeanFactory.
    //创建xml的解析器,这里是一个委托模式
    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);


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


    //这里传一个this进去,因为ApplicationContext是实现了ResourceLoader接口的
    beanDefinitionReader.setResourceLoader(this);
    beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));


    // Allow a subclass to provide custom initialization of the reader,
    // then proceed with actually loading the bean definitions.
    initBeanDefinitionReader(beanDefinitionReader);


    //主要看这个方法  
    loadBeanDefinitions(beanDefinitionReader);
  }
// AbstractXmlApplicationContext.java
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
    Resource[] configResources = getConfigResources();
    if (configResources != null) {
      reader.loadBeanDefinitions(configResources);
    }
    //获取需要加载的xml配置文件
    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
      reader.loadBeanDefinitions(configLocations);
    }
  }
// AbstractBeanDefinitionReader.java
@Override
  public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
    Assert.notNull(locations, "Location array must not be null");
    int count = 0;
    //配置文件有多个,加载多个配置文件
    for (String location : locations) {
      count += loadBeanDefinitions(location);
    }
    return count;
  }
// AbstractBeanDefinitionReader.java
public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
    ResourceLoader resourceLoader = getResourceLoader();
    if (resourceLoader == null) {
      throw new BeanDefinitionStoreException(
          "Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
    }


    if (resourceLoader instanceof ResourcePatternResolver) {
      // Resource pattern matching available.
      try {
        //把字符串类型的xml文件路径,形如:classpath*:user/**/*-context.xml,转换成Resource对象类型,其实就是用流
        //的方式加载配置文件,然后封装成Resource对象,不重要,可以不看
        Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);


        //主要看这个方法
        int count = loadBeanDefinitions(resources);
        if (actualResources != null) {
          Collections.addAll(actualResources, resources);
        }
        if (logger.isTraceEnabled()) {
          logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
        }
        return count;
      }
      catch (IOException ex) {
        throw new BeanDefinitionStoreException(
            "Could not resolve bean definition resource pattern [" + location + "]", ex);
      }
    }
    else {
      // Can only load single resources by absolute URL.
      Resource resource = resourceLoader.getResource(location);
      int count = loadBeanDefinitions(resource);
      if (actualResources != null) {
        actualResources.add(resource);
      }
      if (logger.isTraceEnabled()) {
        logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
      }
      return count;
    }
  }
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
    Assert.notNull(encodedResource, "EncodedResource must not be null");
    if (logger.isTraceEnabled()) {
      logger.trace("Loading XML bean definitions from " + encodedResource);
    }


    Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
    if (currentResources == null) {
      currentResources = new HashSet<>(4);
      this.resourcesCurrentlyBeingLoaded.set(currentResources);
    }
    if (!currentResources.add(encodedResource)) {
      throw new BeanDefinitionStoreException(
          "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
    }
    try {
      //获取Resource对象中的xml文件流对象
      InputStream inputStream = encodedResource.getResource().getInputStream();
      try {
        //InputSource是jdk中的sax xml文件解析对象
        InputSource inputSource = new InputSource(inputStream);
        if (encodedResource.getEncoding() != null) {
          inputSource.setEncoding(encodedResource.getEncoding());
        }
        //主要看这个方法 
        return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
      }
      finally {
        inputStream.close();
      }
    }
    catch (IOException ex) {
      throw new BeanDefinitionStoreException(
          "IOException parsing XML document from " + encodedResource.getResource(), ex);
    }
    finally {
      currentResources.remove(encodedResource);
      if (currentResources.isEmpty()) {
        this.resourcesCurrentlyBeingLoaded.remove();
      }
    }
  }
// 开始将XML解析封装为Document对象
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
      throws BeanDefinitionStoreException {


    try {
      //把inputSource 封装成Document文件对象,这是jdk的API
      Document doc = doLoadDocument(inputSource, resource);


      //主要看这个方法,根据解析出来的document对象,拿到里面的标签元素封装成BeanDefinition
      int count = registerBeanDefinitions(doc, resource);
      if (logger.isDebugEnabled()) {
        logger.debug("Loaded " + count + " bean definitions from " + resource);
      }
      return count;
    }
    catch (BeanDefinitionStoreException ex) {
      throw ex;
    }
    catch (SAXParseException ex) {
      throw new XmlBeanDefinitionStoreException(resource.getDescription(),
          "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
    }
    catch (SAXException ex) {
      throw new XmlBeanDefinitionStoreException(resource.getDescription(),
          "XML document from " + resource + " is invalid", ex);
    }
    catch (ParserConfigurationException ex) {
      throw new BeanDefinitionStoreException(resource.getDescription(),
          "Parser configuration exception parsing XML from " + resource, ex);
    }
    catch (IOException ex) {
      throw new BeanDefinitionStoreException(resource.getDescription(),
          "IOException parsing XML document from " + resource, ex);
    }
    catch (Throwable ex) {
      throw new BeanDefinitionStoreException(resource.getDescription(),
          "Unexpected exception parsing XML document from " + resource, ex);
    }
  }
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
    //又来一记委托模式,BeanDefinitionDocumentReader委托这个类进行document的解析
    BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
    int countBefore = getRegistry().getBeanDefinitionCount();
    //主要看这个方法,createReaderContext(resource) XmlReaderContext上下文,封装了XmlBeanDefinitionReader对象
    documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
    return getRegistry().getBeanDefinitionCount() - countBefore;
  }
// DefaultBeanDefinitionDocumentReader.java
  @Override
  public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
    this.readerContext = readerContext;
    //主要看这个方法,把root节点传进去
    doRegisterBeanDefinitions(doc.getDocumentElement());
  }
// 解析完开始准备注册传入root
protected void doRegisterBeanDefinitions(Element root) {
    // Any nested <beans> elements will cause recursion in this method. In
    // order to propagate and preserve <beans> default-* attributes correctly,
    // keep track of the current (parent) delegate, which may be null. Create
    // the new (child) delegate with a reference to the parent for fallback purposes,
    // then ultimately reset this.delegate back to its original (parent) reference.
    // this behavior emulates a stack of delegates without actually necessitating one.
    BeanDefinitionParserDelegate parent = this.delegate;
    this.delegate = createDelegate(getReaderContext(), root, parent);


    if (this.delegate.isDefaultNamespace(root)) {
      String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
      if (StringUtils.hasText(profileSpec)) {
        String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
            profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
        // We cannot use Profiles.of(...) since profile expressions are not supported
        // in XML config. See SPR-12458 for details.
        if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
          if (logger.isDebugEnabled()) {
            logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
                "] not matching: " + getReaderContext().getResource());
          }
          return;
        }
      }
    }


    preProcessXml(root);


    //主要看这个方法,标签具体解析过程
    parseBeanDefinitions(root, this.delegate);
    postProcessXml(root);


    this.delegate = parent;
  }
// 解析标签
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
    if (delegate.isDefaultNamespace(root)) {
      NodeList nl = root.getChildNodes();
      for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
          Element ele = (Element) node;
          if (delegate.isDefaultNamespace(ele)) {


            //默认标签解析
            parseDefaultElement(ele, delegate);
          }
          else {


            //自定义标签解析
            delegate.parseCustomElement(ele);
          }
        }
      }
    }
    else {
      delegate.parseCustomElement(root);
    }
  }
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
    //import标签解析  重要程度 1 ,可看可不看
    if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
      importBeanDefinitionResource(ele);
    }
    //alias标签解析 别名标签  重要程度 1 ,可看可不看
    else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
      processAliasRegistration(ele);
    }
    //bean标签,重要程度  5,必须看
    else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
      processBeanDefinition(ele, delegate);
    }
    else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
      // recurse
      doRegisterBeanDefinitions(ele);
    }
  }
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    //重点看这个方法,重要程度 5 ,解析document,封装成BeanDefinition
    BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
    if (bdHolder != null) {


      //该方法功能不重要,设计模式重点看一下,装饰者设计模式,加上SPI设计思想
      bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
      try {


        //完成document到BeanDefinition对象转换后,对BeanDefinition对象进行缓存注册
        // Register the final decorated instance.
        BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
      }
      catch (BeanDefinitionStoreException ex) {
        getReaderContext().error("Failed to register bean definition with name '" +
            bdHolder.getBeanName() + "'", ele, ex);
      }
      // Send registration event.
      getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
    }
  }
public static void registerBeanDefinition(
      BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
      throws BeanDefinitionStoreException {


    // Register bean definition under primary name.
    String beanName = definitionHolder.getBeanName();


    //完成BeanDefinition的注册,重点看,重要程度 5
    registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());


    //建立别名和 id的映射,这样就可以根据别名获取到id
    // Register aliases for bean name, if any.
    String[] aliases = definitionHolder.getAliases();
    if (aliases != null) {
      for (String alias : aliases) {
        registry.registerAlias(beanName, alias);
      }
    }
  }
// 哇哇 BD注册最后的调用
@Override
  public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
      throws BeanDefinitionStoreException {


    Assert.hasText(beanName, "Bean name must not be empty");
    Assert.notNull(beanDefinition, "BeanDefinition must not be null");


    if (beanDefinition instanceof AbstractBeanDefinition) {
      try {
        ((AbstractBeanDefinition) beanDefinition).validate();
      }
      catch (BeanDefinitionValidationException ex) {
        throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
            "Validation of bean definition failed", ex);
      }
    }


    //先判断BeanDefinition是否已经注册
    BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
    if (existingDefinition != null) {
      if (!isAllowBeanDefinitionOverriding()) {
        throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
      }
      else if (existingDefinition.getRole() < beanDefinition.getRole()) {
        // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
        if (logger.isInfoEnabled()) {
          logger.info("Overriding user-defined bean definition for bean '" + beanName +
              "' with a framework-generated bean definition: replacing [" +
              existingDefinition + "] with [" + beanDefinition + "]");
        }
      }
      else if (!beanDefinition.equals(existingDefinition)) {
        if (logger.isDebugEnabled()) {
          logger.debug("Overriding bean definition for bean '" + beanName +
              "' with a different definition: replacing [" + existingDefinition +
              "] with [" + beanDefinition + "]");
        }
      }
      else {
        if (logger.isTraceEnabled()) {
          logger.trace("Overriding bean definition for bean '" + beanName +
              "' with an equivalent definition: replacing [" + existingDefinition +
              "] with [" + beanDefinition + "]");
        }
      }
      this.beanDefinitionMap.put(beanName, beanDefinition);
    }
    else {
      if (hasBeanCreationStarted()) {
        // Cannot modify startup-time collection elements anymore (for stable iteration)
        synchronized (this.beanDefinitionMap) {
          this.beanDefinitionMap.put(beanName, beanDefinition);
          List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
          updatedDefinitions.addAll(this.beanDefinitionNames);
          updatedDefinitions.add(beanName);
          this.beanDefinitionNames = updatedDefinitions;
          if (this.manualSingletonNames.contains(beanName)) {
            Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
            updatedSingletons.remove(beanName);
            this.manualSingletonNames = updatedSingletons;
          }
        }
      }
      else {
        //把beanDefinition缓存到map中
        // Still in startup registration phase
        this.beanDefinitionMap.put(beanName, beanDefinition);


        //把beanName放到beanDefinitionNames list中,这个list着重记住,bean实例化的时候需要用到
        this.beanDefinitionNames.add(beanName);
        this.manualSingletonNames.remove(beanName);
      }
      this.frozenBeanDefinitionNames = null;
    }


    if (existingDefinition != null || containsSingleton(beanName)) {
      resetBeanDefinition(beanName);
    }
  }

上面就是一个个方法跟到,beanDefinition注册的过程。

建议大家一步一步跟下去看看。刚开始看起来比较费劲,建议多看几遍哦!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值