[ClassPathXmlApplicationContext] 方式扫描[Bean]

xml与注解
public void test4() {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        AnnotationConfigApplicationContext applicationContext1 = new AnnotationConfigApplicationContext("com.enjoy.chen");
        CircularC circularA = applicationContext.getBean(CircularC.class);
        CircularD circularB = applicationContext.getBean(CircularD.class);
    }

Bean的定义

1、通过xml的方式,如以上代码块中的第二行,我们通过去加载xml配置,通过对bean标签的解析从而得到bean的相关信息。

<bean id="zantong" class="com.enjoy.jack.factorymethod.ZanTong"/>
<bean id="huaqiao" factory-bean="zantong" factory-method="zanTongSay"/>

2、通过注解的方式,通过去扫描指定包路径下的类,以此获取到bean。不管是@Component,@Configuration还是@Bean都是注解的一种方式,不应该分开看。

传统标签解析

现在随着“约定大于配置”思想,注解使用越来越多,而标签基本也只是在一些老项目中在维护。但注解是由标签的基础上而来,了解标签还是十分必要的,我的学习将会从Spring解析传统标签开始。
ClassPathXmlApplicationContext 在其内部的构造方法里启动了Spring容器。

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)throws BeansException {
    super(parent);
    setConfigLocations(configLocations);
    if (refresh) {
        //Spring核心方法,启动Spring容器
        refresh();
    }
}

在refresh方法中调用了obtainFreshBeanFactory方法,该方法去创建了BeanFactory,并完成对xml的解析。
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

    /**
     * Tell the subclass to refresh the internal bean factory.
     * 源码的注释很明白的说明了这里是去刷新内部的Bean Factory
     */
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        //核心方法
        refreshBeanFactory();
        return getBeanFactory();
    }

refreshBeanFactory是一个抽象的方法,这里采用了模板设计模式。具体由顶层父类定义抽象方法,具体是由子类去实现(钩子方法)。refreshBeanFactory现在交给了AbstractRefreshableApplicationContext类具体实现,方法中判断BeanFactory并设置是否覆盖以及是否循环依赖。

    /**
     * 此实现执行此上下文的底层bean工厂的实际刷新,关闭以前的bean工厂(如果有的话),
     * 并为上下文生命周期的下一阶段初始化一个新鲜的bean工厂。
     */
    @Override
    protected final void refreshBeanFactory() throws BeansException {
        //如果BeanFactory不为空,则清除BeanFactory和里面的实例
        if (hasBeanFactory()) {
            destroyBeans();
            closeBeanFactory();
        }
        try {
            //BeanFactory 实例工厂
            DefaultListableBeanFactory beanFactory = createBeanFactory();
            beanFactory.setSerializationId(getId());
            //设置是否可以循环依赖 allowCircularReferences
            //是否允许使用相同名称重新注册不同的bean实现.
            customizeBeanFactory(beanFactory);
            //解析xml,并把xml中的标签封装成BeanDefinition对象
            loadBeanDefinitions(beanFactory);
            this.beanFactory = beanFactory;
        }
        catch (IOException ex) {
            throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
        }
    }

重点在loadBeanDefinitions(beanFactory)方法,方法解析xml中的<bean/>标签并封装成BeanDefinition。

    /**
     * 通过XmlBeanDefinitionReader加载bean定义。
     */
    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // Create a new XmlBeanDefinitionReader for the given BeanFactory.
        //创建xml的解析器,这里是一个委托模式
        //将对xml文件的解析交给XmlBeanDefinitionReader对象
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
        //主要看这个方法
        loadBeanDefinitions(beanDefinitionReader);
    }

在方法内创建了xml解析器,并将解析器往下传,在加载xml配置文件后,交由xml解析器进行解析。

    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
        //第一次进入时 configResources 为空
        Resource[] configResources = getConfigResources();
        if (configResources != null) {
            reader.loadBeanDefinitions(configResources);
        }
        //获取需要加载的xml配置文件,可以是多个xml配置文件,所以为String[]
        String[] configLocations = getConfigLocations();
        if (configLocations != null) {
            //xml解析器根据文件名进行解析
            reader.loadBeanDefinitions(configLocations);
        }
    }

在这里就会去加载配置文件名称,配置文件名称在还未启动Spring容器就已经设置了,在第三个代码块中的setConfigLocations(configLocations)方法。拿到xml配置文件名称,接下来就是挨个进行解析。

    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;
    }
    public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
        ResourceLoader resourceLoader = getResourceLoader();
        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);
            }
        }
    }
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
        ...
        //获取Resource对象中的xml文件流对象
        try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
            //InputSource是jdk中的sax xml文件解析对象
            InputSource inputSource = new InputSource(inputStream);
            if (encodedResource.getEncoding() != null) {
                inputSource.setEncoding(encodedResource.getEncoding());
            }
            //主要看这个方法 
            return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
        }
        ...
    }

这个方法里面主要看两行,1、加载配置文件封装成Resource,2、加载解析Resource。
当方法走到XmlBeanDefinitionReader类时,获取Resource对象的输入流,进而再包装成inputSource对象。

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;
            ...
        }
    }

doLoadBeanDefinitions方法做了两个事,1、把xml包装成了一个Document对象,委托给了DefaultDocumentLoader类,2、对Document的解析,委托给了BeanDefinitionDocumentReader。

    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;
    }
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
        this.readerContext = readerContext;
        //主要看这个方法,把root节点传进去
        doRegisterBeanDefinitions(doc.getDocumentElement());
    }
    /**
     * 在给定的根<beans/>元素中注册每个bean定义.
     */
    @SuppressWarnings("deprecation")  // for Environment.acceptsProfiles(String...)
    protected void doRegisterBeanDefinitions(Element root) {
        ...
        preProcessXml(root);
        //主要看这个方法,标签具体解析过程
        parseBeanDefinitions(root, this.delegate);
        postProcessXml(root);
        this.delegate = parent;
    }
    /**
     * 在文档的根元素下解析元素:"import", "alias", "bean"
     */
    protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
        if (delegate.isDefaultNamespace(root)) {
            //取出根元素下的子元素,放到NodeList对象中
            NodeList nl = root.getChildNodes();
            for (int i = 0; i < nl.getLength(); i++) {
                Node node = nl.item(i);
                //判断节点是否是元素,node可能是空格,制表符等
                if (node instanceof Element) {
                    Element ele = (Element) node;
                    if (delegate.isDefaultNamespace(ele)) {
                        //默认标签解析
                        parseDefaultElement(ele, delegate);
                    }
                    else {
                        //自定义标签解析
                        delegate.parseCustomElement(ele);
                    }
                }
            }
        }
        else {
            delegate.parseCustomElement(root);
        }
    }

到此,就正式开始了对xml配置文件的解析,从上面的代码块中xml的解析又分为了默认标签解析和自定义标签解析,就会进行个分支的学习。
小结一下:要解析配置文件
1、要知道文件路径以及文件名,不然加载什么?
2、获取到文件输入流。包装成能解析的对象。
3、解析包装对象,获取需要的节点信息。
开篇简单的以图例总结一下:


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

推荐阅读更多精彩内容