Spring初始化过程详解

之前有给大家讲到过关于spring容器初始化过程的内容,那么下面要讲的就是整个Spring初始化过程的详解,一起来了解一下吧。

首先编写除一个比较简单的启动类。

之后,打个断点到AbstractApplicationContext当中的refresh()方法当中。

public class Application
{
    public static void main(String[] args)
    {
        // setConfig -> call this.refresh()
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("context.xml");
    }
}

先来看一下,refresh当中都调用了哪些方法:

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)
        {
            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();
        }
    }
}

图文详解!

Spring初始化过程详解

大家可以仔细的去看看上面的图片内容,这个就是整个初始化的大致流程了,希望上面的内容可以对你有所帮助哦!

更多java常见问题及解决方法,请继续关注奇Q工具网来进行了解吧!

推荐阅读:

Spring AOP的应用场景详解

Spring Ioc容器的加载流程是怎样的?加载过程详解

springboot事务回滚要怎么配置?有几种方法?