Spring源码——ClassPathXmlApplicationContext

一、ClassPathXmlApplicationContext的作用

    ClassPathXmlApplicationContext是Spring读取xml最常用的类,它只能读取放在WEB-INF/classes/目录下的配置文件,所以在使用ClassPathXmlApplicationContext的时候可以将配置文件放在项目的原文件夹下面,这样编译的时候会将配置文件拷贝到WEB-INF下面去。如果是Springboot项目,一般要把文件呢放到resources配置文件夹下,才可以被ClassPathXmlApplicationContext读取到。

二、ClassPathXmlApplicationContext类的继承关系

ClassPathXmlApplicationContext 类的继承结构

        PS:蓝色实线为类继承关系、绿色虚线为类实现接口、绿色实线为接口继承接口

三、ClassPathXmlApplicationContext是怎么读取配置文件的

    1、常用的ClassPathXmlApplicationContext使用方式:
         ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring-ioc.xml");
    2、构造方法;

    参数parent是自动传递上下文;
    
    2.1   super(parent);方法一直引用到AbstractApplicationContext中,将ApplicationContext的环境属性设置给本类的环境属性,包括一些profile、系统属性等;

    2.2 this.setConfigLocations(configLocations);  设置xml配置文件地址;

    2.3 refresh()进行初始化工作;
        refresh()方法是用来刷新IOC容器的,此方法会去调用父类的刷新方法,所有的bean都会在此方法中实现加载。

refresh源码

    3、加载Bean
        在 ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();方法执行结束之后,xml中定义的bean就已经加载到IOC容器中了。

obtainFreshBeanFactory源码

if语句逻辑,如果beanFactory存在就销毁关闭,然后在下面重新创建。
DefaultListableBeanFactory类是整个Bean加载的核心部分,是Spring注册加载Bean的默认实现,也是整个Spring IOC的始祖。
红框方法为注册bean

加载Bean

这里实现主要分几个步骤:
    首先判断本类的DefaultListableBeanFactory属性是否为null,如果不为null,就先清除一写跟Bean有关的Map或者List等属性集合
    将BeanFactory设置为null,序列化id设置为null,
    创建DefaultListableBeanFactory,这个类很重要,是springBean初始化的核心类,
    对beanFactory进行设置,bean注册等操作,最后将beanFactory赋值给本类的beanFactory属性
其中customizeBeanFactory只做了两件事,设置bean是否允许覆盖、设置Bean是否允许循环使用。

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
     // 实例化一个用于读取和转化xml文件内容的XmlBeanDefinitionReader
     XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

     // 设置reader的环境属性
     beanDefinitionReader.setEnvironment(this.getEnvironment());
     beanDefinitionReader.setResourceLoader(this);
     beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
     // 通过beanDefinitionReader 加载bean
     initBeanDefinitionReader(beanDefinitionReader);
     loadBeanDefinitions(beanDefinitionReader);
 }


加载资源、加载之前设置的xml配置文件资源
reader.loadBeanDefinitions(configLocations); 循环加载xml文件的Bean,返回Bean总个数,查看加载方法。

3.1 加载入口
   

调用AbstractBeanDefinitionReader中的loadBeanDefinitions(String... locations)方法

    3.2 将xml文件转化为Resource流对象

public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
//获取之前设置的加载起
     ResourceLoader resourceLoader = this.getResourceLoader();
     if (resourceLoader == null) {
         throw new BeanDefinitionStoreException("Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
     } else {
         int count;
//通配符加载器
         if (resourceLoader instanceof ResourcePatternResolver) {
             try {
                 Resource[] resources = ((ResourcePatternResolver)resourceLoader).getResources(location);
                 count = this.loadBeanDefinitions(resources);  // 读取bean
                 if (actualResources != null) {
                     Collections.addAll(actualResources, resources);
                 }
                 if (this.logger.isTraceEnabled()) {
                     this.logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
                 }
                 return count;
             } catch (IOException var6) {
                 throw new BeanDefinitionStoreException("Could not resolve bean definition resource pattern [" + location + "]", var6);
             }
         } else {
            //读取单个绝对路径的配置文件
             Resource resource = resourceLoader.getResource(location);
             count = this.loadBeanDefinitions((Resource)resource);  //进入该方法中
             if (actualResources != null) {
                 actualResources.add(resource);
             }
             if (this.logger.isTraceEnabled()) {
                 this.logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
             }
             return count;
         }
     }
 }

主要步骤:
    1、获取加载起中的Resource[]数组
    2、加载资源中的Bean,返回加载数量   
 3.3 解析xml中的内容并注册bean
        在XmlBeanDefinitionReader中,通过Document doc = doLoadDocument(inputSource, resource),读取Resource流的内容,并封装为Document 对象。然后调用doLoadBeanDefinitions(InputSource inputSource, Resource resource)方法加载bean。

loadBeanDefinitions

    3.4 将XML中的标签内容封装为Element对象
        调用DefaultBeanDefinitionDocumentReader中registerBeanDefinitions(Document doc, XmlReaderContext readerContext)方法。最终,通过委派方式,将Element对象交由BeanDefinitionParserDelegate解析

public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
     this.readerContext = readerContext;
     this.doRegisterBeanDefinitions(doc.getDocumentElement());
 }    

protected void doRegisterBeanDefinitions(Element root) {
     BeanDefinitionParserDelegate parent = this.delegate;
     this.delegate = this.createDelegate(this.getReaderContext(), root, parent);
     if (this.delegate.isDefaultNamespace(root)) {
         String profileSpec = root.getAttribute("profile");
         if (StringUtils.hasText(profileSpec)) {
             String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, ",; ");
             if (!this.getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
                 if (this.logger.isDebugEnabled()) {
                     this.logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec + "] not matching: " + this.getReaderContext().getResource());
                 }
                 return;
              }
         }
     }
     this.preProcessXml(root);   //预处理XML
     this.parseBeanDefinitions(root, this.delegate);  // 解析XML中的<bean>标签
     this.postProcessXml(root);  //后处理XML
     this.delegate = parent;
 }

// 解析XML中<bean>标签
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
     if (delegate.isDefaultNamespace(root)) {
         NodeList nl = root.getChildNodes();  //获取xml中的所有子标签节点
         for(int i = 0; i < nl.getLength(); ++i) {
             Node node = nl.item(i);
             if (node instanceof Element) {   //判断是否是<bean>标签
                 Element ele = (Element)node;  // 将xml标签封装为Element元素
                 if (delegate.isDefaultNamespace(ele)) {
                     this.parseDefaultElement(ele, delegate);  //解析xml标签元素
                 } else {
                     delegate.parseCustomElement(ele);
                 }
             }
         }
     } else {
         delegate.parseCustomElement(root);
     }
 }


private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
     if (delegate.nodeNameEquals(ele, "import")) {        //解析引入其他XML节点
         this.importBeanDefinitionResource(ele);
     } else if (delegate.nodeNameEquals(ele, "alias")) {  // 解析别名节点
         this.processAliasRegistration(ele);
     } else if (delegate.nodeNameEquals(ele, "bean")) {  //解析bean节点
         this.processBeanDefinition(ele, delegate);   
     } else if (delegate.nodeNameEquals(ele, "beans")) {  //解析嵌套bean节点
         this.doRegisterBeanDefinitions(ele);
     }
 }

    3.5 解析BeanDefinitionElement
        在BeanDefinitionParserDelegate中通过parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean)方法,对xml文件中定义的bean做解析。

public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
     String id = ele.getAttribute("id");
     String nameAttr = ele.getAttribute("name");
     List<String> aliases = new ArrayList();
     if (StringUtils.hasLength(nameAttr)) {
         String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, ",; ");
         aliases.addAll(Arrays.asList(nameArr));
     }
     String beanName = id;
     if (!StringUtils.hasText(id) && !aliases.isEmpty()) {
         beanName = (String)aliases.remove(0);
         if (this.logger.isTraceEnabled()) {
             this.logger.trace("No XML 'id' specified - using '" + beanName + "' as bean name and " + aliases + " as aliases");
         }
     }
//检查id是否是唯一值
     if (containingBean == null) {
         this.checkNameUniqueness(beanName, aliases, ele);
     }
//通过id解析得到bean Definition实例
     AbstractBeanDefinition beanDefinition = this.parseBeanDefinitionElement(ele, beanName, containingBean);
     if (beanDefinition != null) {
         if (!StringUtils.hasText(beanName)) {
             try {
                 if (containingBean != null) {
                     beanName = BeanDefinitionReaderUtils.generateBeanName(beanDefinition, this.readerContext.getRegistry(), true);
                 } else {
                     beanName = this.readerContext.generateBeanName(beanDefinition);
                     String beanClassName = beanDefinition.getBeanClassName();
                     if (beanClassName != null && beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() && !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
                         aliases.add(beanClassName);
                     }
                 }
                 if (this.logger.isTraceEnabled()) {
                     this.logger.trace("Neither XML 'id' nor 'name' specified - using generated bean name [" + beanName + "]");
                 }
             } catch (Exception var9) {
                 this.error(var9.getMessage(), ele);
                 return null;
             }
         }
         String[] aliasesArray = StringUtils.toStringArray(aliases);
         return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
     } else {
         return null;
     }
 }


//通过id解析得到bean Definition实例方法
@Nullable
 public AbstractBeanDefinition parseBeanDefinitionElement(Element ele, String beanName, @Nullable BeanDefinition containingBean) {
//通过id实例化BeanFactory对象,并将它放入当前的BeanDefinitionParserDelegate对象的parseState对象属性的LinkedList属性中
     this.parseState.push(new BeanEntry(beanName));
//获取<bean>标签中定义的Class属性
     String className = null;
     if (ele.hasAttribute("class")) {
         className = ele.getAttribute("class").trim();
     }
//获取是否存在父类,及其信息
     String parent = null;
     if (ele.hasAttribute("parent")) {
         parent = ele.getAttribute("parent");
     }
     try {
//通过<bean>标签中定义的类信息创建一个bean
         AbstractBeanDefinition bd = this.createBeanDefinition(className, parent);
// 解析bean对象的实例化相关信息(作用域、懒加载、依赖关系等)
//既<bean ... scope="singleton" lazy-init="true" primary="true" depends-on="emp" init-method="" ...>这些属性
         this.parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
         bd.setDescription(DomUtils.getChildElementValueByTagName(ele, "description"));
//j解析bean中源数据的信息
         this.parseMetaElements(ele, bd);
//解析覆盖的方法
         this.parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
         this.parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
//解析依赖注入信息
         this.parseConstructorArgElements(ele, bd);  //解析构造器参数注入元素
         this.parsePropertyElements(ele, bd);   //解析属性(set)注入元素
         this.parseQualifierElements(ele, bd);   //解析限定(Qualifier)注入元素:当容器中有多个类型相同的bean时,想要用一个属性置顶他们其中的一个进行匹配,常见的是@Autowired联合@Qualifier("beanID")的方式
         bd.setResource(this.readerContext.getResource());
         bd.setSource(this.extractSource(ele));
         AbstractBeanDefinition var7 = bd;
         return var7;
     } catch (ClassNotFoundException var13) {
         this.error("Bean class [" + className + "] not found", ele, var13);
     } catch (NoClassDefFoundError var14) {
         this.error("Class that bean class [" + className + "] depends on not found", ele, var14);
     } catch (Throwable var15) {
         this.error("Unexpected failure during bean definition parsing", ele, var15);
     } finally {
         this.parseState.pop();
     }
     return null;
 }


//创建一个bean
protected AbstractBeanDefinition createBeanDefinition(@Nullable String className, @Nullable String parentName) throws ClassNotFoundException {     
    return BeanDefinitionReaderUtils.createBeanDefinition(parentName, className, this.readerContext.getBeanClassLoader()); 
}

public static AbstractBeanDefinition createBeanDefinition(@Nullable String parentName, @Nullable String className, @Nullable ClassLoader classLoader) throws ClassNotFoundException {
     GenericBeanDefinition bd = new GenericBeanDefinition();
     bd.setParentName(parentName);
     if (className != null) {
         if (classLoader != null) {
//如果使用自定义的classLoader—类加载器,则通过反射加载类信息
             bd.setBeanClass(ClassUtils.forName(className, classLoader));
         } else {
             bd.setBeanClassName(className);
         }
     }
     return bd;
 }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容