ClassPathXmlApplicationContext

1.构造ClassPathXmlApplicationContext

    /**
     * Create a new ClassPathXmlApplicationContext, loading the definitions
     * from the given XML file and automatically refreshing the context.
     * @param configLocation resource location
     * @throws BeansException if context creation failed
     */
    public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
        this(new String[] {configLocation}, true, null);
    }
    public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
            throws BeansException {

        super(parent);
        setConfigLocations(configLocations);
        if (refresh) {
            refresh();
        }
    }

2.AbstractApplicationContext

    @Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();

            // 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) {
                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

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

                // Propagate exception to caller.
                throw ex;
            }
        }
    }
    /**
     * Tell the subclass to refresh the internal bean factory.
     * @return the fresh BeanFactory instance
     * @see #refreshBeanFactory()
     * @see #getBeanFactory()
     */
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        refreshBeanFactory();
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (logger.isDebugEnabled()) {
            logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
        }
        return beanFactory;
    

3.AbstractRefreshableApplicationContext.refreshBeanFactory()

    /**
     * This implementation performs an actual refresh of this context‘s underlying
     * bean factory, shutting down the previous bean factory (if any) and
     * initializing a fresh bean factory for the next phase of the context‘s lifecycle.
     */
    @Override
    protected final void refreshBeanFactory() throws BeansException {
        if (hasBeanFactory()) {
            destroyBeans();
            closeBeanFactory();
        }
        try {
            DefaultListableBeanFactory beanFactory = createBeanFactory();
            beanFactory.setSerializationId(getId());
            customizeBeanFactory(beanFactory);
            loadBeanDefinitions(beanFactory);
            synchronized (this.beanFactoryMonitor) {
                this.beanFactory = beanFactory;
            }
        }
        catch (IOException ex) {
            throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
        }
    }

4.AbstractXmlApplicationContext.loadBeanDefinitions()

    /**
     * Load the bean definitions with the given XmlBeanDefinitionReader.
     * <p>The lifecycle of the bean factory is handled by the {@link #refreshBeanFactory}
     * method; hence this method is just supposed to load and/or register bean definitions.
     * @param reader the XmlBeanDefinitionReader to use
     * @throws BeansException in case of bean registration errors
     * @throws IOException if the required XML document isn‘t found
     * @see #refreshBeanFactory
     * @see #getConfigLocations
     * @see #getResources
     * @see #getResourcePatternResolver
     */
    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
        Resource[] configResources = getConfigResources();
        if (configResources != null) {
            reader.loadBeanDefinitions(configResources);
        }
        String[] configLocations = getConfigLocations();
        if (configLocations != null) {
            reader.loadBeanDefinitions(configLocations);
        }
    }

5.AbstractBeanDefinitionReader.loadBeanDefinitions()

    @Override
    public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
        Assert.notNull(locations, "Location array must not be null");
        int counter = 0;
        for (String location : locations) {
            counter += loadBeanDefinitions(location);
        }
        return counter;
    }

    @Override
    public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
        return loadBeanDefinitions(location, null);
    }

    /**
     * Load bean definitions from the specified resource location.
     * <p>The location can also be a location pattern, provided that the
     * ResourceLoader of this bean definition reader is a ResourcePatternResolver.
     * @param location the resource location, to be loaded with the ResourceLoader
     * (or ResourcePatternResolver) of this bean definition reader
     * @param actualResources a Set to be filled with the actual Resource objects
     * that have been resolved during the loading process. May be {@code null}
     * to indicate that the caller is not interested in those Resource objects.
     * @return the number of bean definitions found
     * @throws BeanDefinitionStoreException in case of loading or parsing errors
     * @see #getResourceLoader()
     * @see #loadBeanDefinitions(org.springframework.core.io.Resource)
     * @see #loadBeanDefinitions(org.springframework.core.io.Resource[])
     */
    public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
        ResourceLoader resourceLoader = getResourceLoader();
        if (resourceLoader == null) {
            throw new BeanDefinitionStoreException(
                    "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
        }

        if (resourceLoader instanceof ResourcePatternResolver) {
            // Resource pattern matching available.
            try {
                Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
                int loadCount = loadBeanDefinitions(resources);
                if (actualResources != null) {
                    for (Resource resource : resources) {
                        actualResources.add(resource);
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
                }
                return loadCount;
            }
            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 loadCount = loadBeanDefinitions(resource);
            if (actualResources != null) {
                actualResources.add(resource);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
            }
            return loadCount;
        }
    }
    @Override
    public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
        Assert.notNull(resources, "Resource array must not be null");
        int counter = 0;
        for (Resource resource : resources) {
            counter += loadBeanDefinitions(resource);
        }
        return counter;
    }

6.XmlBeanDefinitionReader.loadBeanDefinitions(Resource resource)

    /**
     * Load bean definitions from the specified XML file.
     * @param resource the resource descriptor for the XML file
     * @return the number of bean definitions found
     * @throws BeanDefinitionStoreException in case of loading or parsing errors
     */
    @Override
    public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
        return loadBeanDefinitions(new EncodedResource(resource));
    }
时间: 2024-10-14 04:28:43

ClassPathXmlApplicationContext的相关文章

The constructor ClassPathXmlApplicationContext(String) refers to the missing type BeansException

"The constructor ClassPathXmlApplicationContext(String) refers to the missing type BeansException" "构造函数ClassPathXmlApplicationContext(字符串)是指缺失类型BeansException" 出现错误的原因:jar没有正确引入,即使表面上你能import包. import org.junit.Test; import org.spring

ClassPathXmlApplicationContext和FileSystemXmlApplicationContext路径问题

1.Spring中ClassPathXmlApplicationContext问题 ClassPathXmlApplicationContext是从ClassPath类加载路径下加载对应的xml文件的. (1)一般使用classpath路径,前缀可加可不加, 例如:new ClassPathXmlApplicationContext("classpath:conf/core/train-servlet.xml") (2)也可以使用绝对路径,加上file:表示绝对路径,一般不建议使用绝对

Spring中ClassPathXmlApplicationContext类的简单使用

一.简单的用ApplicationContext做测试的话,获得Spring中定义的Bean实例(对象).可以用: ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");RegisterDAO registerDAO = (RegisterDAO)ac.getBean("RegisterDAO"); 如果是两个以上:ApplicationContext

初学spring,关于classpath,ClassPathXmlApplicationContext()方法的

今天在写书上的一个demo时候,发现ClassPathXmlApplicationContext(stringg str)这个方法中的str是以src文件为起始地址的,而且他的更目录也是在src这一层,不会再上达到项目文件的目录层:FileSystemXmlApplicationContext(string str)方法中的str是以项目目层为起始地址和根目录,且不会再上达到系统的其他目录层上去.例如要使用ClassPathXmlApplicationContext(string str)时,.

spring mvc使用ClassPathXmlApplicationContext或FileSystemXmlApplicationContext和XmlWebApplicationContext类的操作其中 XmlWebApplicationContext是专为Web工程定制的。

一.简单的用ApplicationContext做测试的话,获得Spring中定义的Bean实例(对象).可以用: ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");RegisterDAO registerDAO = (RegisterDAO)ac.getBean("RegisterDAO"); 如果是两个以上:ApplicationContext

FileSystemXmlApplicationContext、ClassPathXmlApplicationContext和XmlWebApplicationContext简介

引用:http://blog.csdn.net/souichiro/article/details/6068552 今天在用Spring时遇到一个问题,提示找不到applicationContext.xml文件.原来是在加载这个文件时调用的方法不太合适,所以造成了程序找不到项目下的xml配置文件. 我们常用的加载context文件的方法有如下三个: 1.FileSystemXmlApplicationContext 这个方法是从文件绝对路径加载配置文件,例如: ApplicationContex

在程序中用new ClassPathXmlApplicationContext()的注意事项

问题背景:在我们的web程序中,用spring来管理各个实例(bean), 有时在程序中为了使用已被实例化的bean, 通常会用到这样的代码: [java] view plain copy ApplicationContext appContext = new ClassPathXmlApplicationContext("classpath:META-INF/spring/applicationContext-common.xml"); ApplicationContext appC

ClassPathXmlApplicationContext类

org.springframework.context.support Class ClassPathXmlApplicationContext java.lang.Objectorg.springframework.core.io.DefaultResourceLoaderorg.springframework.context.support.AbstractApplicationContextorg.springframework.context.support.AbstractRefres

[转] FileSystemXmlApplicationContext、ClassPathXmlApplicationContext和XmlWebApplicationContext简介

今天在用Spring时遇到一个问题,提示找不到applicationContext.xml文件.原来是在加载这个文件时调用的方法不太合适,所以造成了程序找不到项目下的xml配置文件. 我们常用的加载context文件的方法有如下三个: 1.FileSystemXmlApplicationContext 这个方法是从文件绝对路径加载配置文件,例如: ApplicationContext ctx = new FileSystemXmlApplicationContext( "G:/Test/appl