java培训
搜索分类

pring ioc容器初始化过程是怎样的详解

赋能网 2023-05-09 50

下面要给大家带来的就是springioc理解和初始化过程方面的内容,你对于这点有足够的了解吗?一起通过下文来进行学习吧。

下面对spring ioc容器的启动过程进行一下详细的介绍:

启动容器

AnnotationConfigApplicationContext anno = new AnnotationConfigApplicationContext(MainConfig.class);

进入AnnotationConfigApplicationContext类当中。

代码,scan方法对包进行扫描,进行refresh方法,容器的刷新和IOC容器的创建。

 public AnnotationConfigApplicationContext(String...basePackages)
 {
     this();
     this.scan(basePackages);
     this.refresh();
 }

首先的话是refresh方法加入线程安全锁,之后再调用prepareRefresh方法中,进行类加载前的刷新前的预处理。

public void refresh() throws BeansException, IllegalStateException
{
    synchronized(this.startupShutdownMonitor)
    { //加入线程安全锁
        this.prepareRefresh();
        ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
        this.prepareBeanFactory(beanFactory);
        try
        {
            this.postProcessBeanFactory(beanFactory);
            this.invokeBeanFactoryPostProcessors(beanFactory);
            this.registerBeanPostProcessors(beanFactory);
            this.initMessageSource();
            this.initApplicationEventMulticaster();
            this.onRefresh();
            this.registerListeners();
            this.finishBeanFactoryInitialization(beanFactory);
            this.finishRefresh();
        }
        catch (BeansException var9)
        {
            if (this.logger.isWarnEnabled())
            {
                this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
            }
            this.destroyBeans();
            this.cancelRefresh(var9);
            throw var9;
        }
        finally
        {
            this.resetCommonCaches();
        }
    }
}

进入prepareRefresh方法中。

这个方法是由AbstractApplicationContext抽象类提供的公共方法。

protected void prepareRefresh()
{
    this.startupDate = System.currentTimeMillis(); //记录开始时间
    this.closed.set(false); //记录状态,当前容器关不了吗?
    this.active.set(true);
    if (this.logger.isInfoEnabled())
    {
        this.logger.info("Refreshing " + this);
    }
    this.initPropertySources(); //初始化一些属性设计(此方法为空,留在子类做事情的,由子类来自定义属性设置)
    this.getEnvironment()
        .validateRequiredProperties(); //检验属性的合法性
    this.earlyApplicationEvents = new linkedHashSet(); //保存容器中早期的一些事件
}

通过obtainFreshBeanFactory方法获取BeanFactory。

这个方法一个是refreshBeanFactory方法另一个是getBeanFactory方法。

protected ConfigurableListableBeanFactory obtainFreshBeanFactory()
{
    this.refreshBeanFactory(); //刷新BeanFactory
    ConfigurableListableBeanFactory beanFactory = this.getBeanFactory(); //获取BeanFactory的对象
    if (this.logger.isDebugEnabled())
    {
        this.logger.debug("Bean factory for " + this.getDisplayName() + ": " + beanFactory);
    }
    return beanFactory;
}

进入refreshBeanFactory方式当中。

这个方法是AbstractApplicationContext类提供一个抽象的方法,GenericApplicationContext类实现了这个方法,设置了id标识并创建beanFactory对象。

protected final void refreshBeanFactory() throws IllegalStateException
{
    if (!this.refreshed.compareAndSet(false, true))
    {
        throw new IllegalStateException("GenericApplicationContext does not support multiple refresh attempts: just call refresh once");
    }
    else
    {
        this.beanFactory.setSerializationId(this.getId());
    }
}

现在执行this.prepareBeanFactory(beanFactory)方法,这个方法BeanFactory的预准备工作(对beanFactory进行设置)。

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory)
{
    beanFactory.setBeanClassLoader(this.getClassLoader()); //设置BeanFactory的类加载器
    beanFactory.setBeanexpressionResolver(new StandardBeanexpressionResolver(beanFactory.getBeanClassLoader())); //支持表达式解析器
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, this.getEnvironment()));
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); //设置PostProcessorf
    //设置忽略的自动装配的接口
    beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
    beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
    beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
    beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
    //注册可以解析自动装配;我们能直接在任何组件中自动注入
    //BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); //添加编译时的AspectJ
    if (beanFactory.containsBean("loadTimeWeaver"))
    {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
    if (!beanFactory.containsLocalBean("environment"))
    { //环境
        beanFactory.registerSingleton("environment", this.getEnvironment());
    }
    if (!beanFactory.containsLocalBean("systemProperties"))
    { //系统属性
        beanFactory.registerSingleton("systemProperties", this.getEnvironment()
            .getSystemProperties());
    }
    if (!beanFactory.containsLocalBean("systemEnvironment"))
    { //系统环境信息
        beanFactory.registerSingleton("systemEnvironment", this.getEnvironment()
            .getSystemEnvironment());
    }
}

this.postProcessBeanFactory(beanFactory)方法对BeanFactory准备工作完成之后,进行的后置处理工作。

方法为空。

子类通过重写这个方法在BeanFactory创建并且准备完成以后做进一步的设置。

上面的内容是BeanFactory的创建和预准备工作。

this.invokeBeanFactoryPostProcessors(beanFactory)方法进行BeanFactory的后置处理器。在BeanFactory标准初始化之后执行的。

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory)
{
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, this.getBeanFactoryPostProcessors());
    if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean("loadTimeWeaver"))
    {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
}

执行BeanFactoryProcessorr的方法。

跟进这个方法。

public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List < BeanFactoryPostProcessor > beanFactoryPostProcessors)
{
    Set < String > processedBeans = new HashSet();
    int var9;
    ArrayList currentRegistryProcessors;
    String[] postProcessorNames;
    if (beanFactory instanceof BeanDefinitionRegistry)
    { //先判断BeanFactory是不是BeanDefinitionRegistry类型
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        List < BeanFactoryPostProcessor > regularPostProcessors = new linkedList();
        List < BeanDefinitionRegistryPostProcessor > registryProcessors = new linkedList();
        Iterator var6 = beanFactoryPostProcessors.iterator();
        while (var6.hasNext())
        {
            BeanFactoryPostProcessor postProcessor = (BeanFactoryPostProcessor) var6.next();
            if (postProcessor instanceof BeanDefinitionRegistryPostProcessor)
            {
                BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
                registryProcessor.postProcessBeanDefinitionRegistry(registry);
                registryProcessors.add(registryProcessor);
            }
            else
            {
                regularPostProcessors.add(postProcessor);
            }
        }
        currentRegistryProcessors = new ArrayList();
        postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); //获取BeanDefinitionRegistryPostProcessor
        String[] var18 = postProcessorNames;
        var9 = postProcessorNames.length;
        int var10;
        String ppName;
        //遍历所有的BeanDifinitionRgPostProcessor
        for (var10 = 0; var10 < var9; ++var10)
        {
            ppName = var18[var10];
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class))
            { //判断是否实现了PriortyOrder接口
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName); //将处理过的bean存储起来
            }
        }
        sortPostProcessors(currentRegistryProcessors, beanFactory); //优先级进行排序
        registryProcessors.addAll(currentRegistryProcessors);
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); //进行执行
        currentRegistryProcessors.clear(); //清楚
        //在执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor
        postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        var18 = postProcessorNames;
        var9 = postProcessorNames.length;
        for (var10 = 0; var10 < var9; ++var10)
        {
            ppName = var18[var10];
            if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class))
            {
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        registryProcessors.addAll(currentRegistryProcessors);
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();
        boolean reiterate = true;
        while (reiterate)
        {
            reiterate = false;
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            String[] var21 = postProcessorNames;
            var10 = postProcessorNames.length;
            for (int var28 = 0; var28 < var10; ++var28)
            {
                String ppName = var21[var28];
                if (!processedBeans.contains(ppName))
                {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                    reiterate = true;
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();
        }
        invokeBeanFactoryPostProcessors((Collection) registryProcessors, (ConfigurableListableBeanFactory) beanFactory);
        invokeBeanFactoryPostProcessors((Collection) regularPostProcessors, (ConfigurableListableBeanFactory) beanFactory);
    }
    else
    {
        invokeBeanFactoryPostProcessors((Collection) beanFactoryPostProcessors, (ConfigurableListableBeanFactory) beanFactory);
    }
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
    List < BeanFactoryPostProcessor > priorityOrderedPostProcessors = new ArrayList();
    List < String > orderedPostProcessorNames = new ArrayList();
    currentRegistryProcessors = new ArrayList();
    postProcessorNames = postProcessorNames;
    int var22 = postProcessorNames.length;
    String ppName;
    for (var9 = 0; var9 < var22; ++var9)
    {
        ppName = postProcessorNames[var9];
        if (!processedBeans.contains(ppName))
        {
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class))
            {
                priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
            }
            else if (beanFactory.isTypeMatch(ppName, Ordered.class))
            {
                orderedPostProcessorNames.add(ppName);
            }
            else
            {
                currentRegistryProcessors.add(ppName);
            }
        }
    }
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors((Collection) priorityOrderedPostProcessors, (ConfigurableListableBeanFactory) beanFactory);
    List < BeanFactoryPostProcessor > orderedPostProcessors = new ArrayList();
    Iterator var23 = orderedPostProcessorNames.iterator();
    while (var23.hasNext())
    {
        String postProcessorName = (String) var23.next();
        orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors((Collection) orderedPostProcessors, (ConfigurableListableBeanFactory) beanFactory);
    List < BeanFactoryPostProcessor > nonOrderedPostProcessors = new ArrayList();
    Iterator var26 = currentRegistryProcessors.iterator();
    while (var26.hasNext())
    {
        ppName = (String) var26.next();
        nonOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
    }
    invokeBeanFactoryPostProcessors((Collection) nonOrderedPostProcessors, (ConfigurableListableBeanFactory) beanFactory);
    beanFactory.clearmetadataCache();
}

invokeBeanDefinitionRegistryPostProcessors方法中,在执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor;

private static void invokeBeanDefinitionRegistryPostProcessors(Collection < ? extends BeanDefinitionRegistryPostProcessor > postProcessors, BeanDefinitionRegistry registry)
{
    Iterator var2 = postProcessors.iterator();
    while (var2.hasNext())
    {
        BeanDefinitionRegistryPostProcessor postProcessor = (BeanDefinitionRegistryPostProcessor) var2.next();
        postProcessor.postProcessBeanDefinitionRegistry(registry);
    }
}

this.registerBeanPostProcessors(beanFactory)这个方法为注册BeanPostProcessor(Bean的后置处理器)。

{
    //获取所有的后置处理器
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    beanFactory.addBeanPostProcessor(new PostProcessorRegistrationDelegate.BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
    List < BeanPostProcessor > priorityOrderedPostProcessors = new ArrayList();
    List < BeanPostProcessor > internalPostProcessors = new ArrayList();
    List < String > orderedPostProcessorNames = new ArrayList();
    List < String > nonOrderedPostProcessorNames = new ArrayList();
    String[] var8 = postProcessorNames;
    int var9 = postProcessorNames.length;
    String ppName;
    BeanPostProcessor pp;
    //循环所有的后置处理器,进行优先级的处理
    for (int var10 = 0; var10 < var9; ++var10)
    {
        ppName = var8[var10];
        if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class))
        { //判断是否是PriorityOrdered类型的类添加到priorityOrderedPostProcessors集合中
            pp = (BeanPostProcessor) beanFactory.getBean(ppName, BeanPostProcessor.class);
            priorityOrderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor)
            {
                internalPostProcessors.add(pp);
            }
        }
        else if (beanFactory.isTypeMatch(ppName, Ordered.class))
        { //判断是否是Ordered类型添加到orderedPostProcessorNames集合中
            orderedPostProcessorNames.add(ppName);
        }
        else
        {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }
    //对priorityOrderedPostProcessors进行排序
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);、
    registerBeanPostProcessors(beanFactory, (List) priorityOrderedPostProcessors);
    List < BeanPostProcessor > orderedPostProcessors = new ArrayList();
    Iterator var14 = orderedPostProcessorNames.iterator();
    while (var14.hasNext())
    {
        String ppName = (String) var14.next();
        BeanPostProcessor pp = (BeanPostProcessor) beanFactory.getBean(ppName, BeanPostProcessor.class);
        orderedPostProcessors.add(pp); //添加到orderedPostProcessors中
        //MergedBeanDefinitionPostProcessor则是在合并处理Bean定义的时候的回调。也基本是框架内部使用的,
        if (pp instanceof MergedBeanDefinitionPostProcessor)
        {
            internalPostProcessors.add(pp);
        }
    }
    //对orderedPostProcessors进行排序
    sortPostProcessors(orderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, (List) orderedPostProcessors);
    List < BeanPostProcessor > nonOrderedPostProcessors = new ArrayList();
    Iterator var17 = nonOrderedPostProcessorNames.iterator();
    while (var17.hasNext())
    {
        ppName = (String) var17.next();
        pp = (BeanPostProcessor) beanFactory.getBean(ppName, BeanPostProcessor.class);
        nonOrderedPostProcessors.add(pp);
        //MergedBeanDefinitionPostProcessor则是在合并处理Bean定义的时候的回调。也基本是框架内部使用的,
        if (pp instanceof MergedBeanDefinitionPostProcessor)
        {
            internalPostProcessors.add(pp);
        }
    }
    registerBeanPostProcessors(beanFactory, (List) nonOrderedPostProcessors);
    sortPostProcessors(internalPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, (List) internalPostProcessors);
    //注册一个ApplicationListenerDetector;来在Bean创建完成后检查是否是ApplicationListener
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

this.initMessageSource()方法为初始化MessageSource组件(做国际化,消息绑定,消息解析)。

protected void initMessageSource()
{
    //获取Beanfactory
    ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
    //判断beanFactory中是否存在messageSource类
    if (beanFactory.containsLocalBean("messageSource"))
    {
        //获取messageSource类
        this.messageSource = (MessageSource) beanFactory.getBean("messageSource", MessageSource.class);
        if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource)
        {
            HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
            if (hms.getParentMessageSource() == null)
            {
                hms.setParentMessageSource(this.getInternalParentMessageSource());
            }
        }
        if (this.logger.isDebugEnabled())
        {
            this.logger.debug("Using MessageSource [" + this.messageSource + "]");
        }
    }
    else
    {
        //如果不存在,new一个DelegatingMessageSource 
        DelegatingMessageSource dms = new DelegatingMessageSource();
        dms.setParentMessageSource(this.getInternalParentMessageSource());
        this.messageSource = dms;
        beanFactory.registerSingleton("messageSource", this.messageSource);
        if (this.logger.isDebugEnabled())
        {
            this.logger.debug("Unable to locate MessageSource with name messageSource: using default [" + this.messageSource + "]");
        }
    }
}

this.initApplicationEventMulticaster方法为初始化事件派发器。

protected void initApplicationEventMulticaster()
{
    ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
    //判断工厂是否存在applicationEventMulticaster的applicationEventMulticaster
    if (beanFactory.containsLocalBean("applicationEventMulticaster"))
    {
        this.applicationEventMulticaster = (ApplicationEventMulticaster) beanFactory.getBean("applicationEventMulticaster", ApplicationEventMulticaster.class);
        if (this.logger.isDebugEnabled())
        {
            this.logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
        }
    }
    else
    {
        //如果不存在,自己创建一个DelegatingMessageSource
        this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        beanFactory.registerSingleton("applicationEventMulticaster", this.applicationEventMulticaster);
        if (this.logger.isDebugEnabled())
        {
            this.logger.debug("Unable to locate ApplicationEventMulticaster with name applicationEventMulticaster: using default [" + this.applicationEventMulticaster + "]");
        }
    }
}

onrefresh();//空方法,留给子容器(子类),子类重写这个方法,在容器刷新的时候可以自定义逻辑。

 protected void onRefresh() throws BeansException
 {}

this.registerListeners()方法将容器中所有项目里面的ApplicationListener注册进来。

protected void registerListeners()
{
    Iterator var1 = this.getApplicationListeners()
        .iterator(); //获取时间派发器中的监听
    while (var1.hasNext())
    {
        ApplicationListener < ? > listener = (ApplicationListener) var1.next();
        //将监听添加到事件派发器中 
        this.getApplicationEventMulticaster()
            .addApplicationListener(listener); //添加监听
    }
    //从容器中获取监听
    String[] listenerBeanNames = this.getBeanNamesForType(ApplicationListener.class, true, false);
    String[] var7 = listenerBeanNames;
    int var3 = listenerBeanNames.length;
    for (int var4 = 0; var4 < var3; ++var4)
    {
        String listenerBeanName = var7[var4];
        //将监听添加到事件派发器中            this.getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
    }
    Set < ApplicationEvent > earlyEventsToProcess = this.earlyApplicationEvents;
    this.earlyApplicationEvents = null;
    if (earlyEventsToProcess != null)
    {
        Iterator var9 = earlyEventsToProcess.iterator();
        while (var9.hasNext())
        {
            ApplicationEvent earlyEvent = (ApplicationEvent) var9.next();
            //派发之前步骤产生的事件
            this.getApplicationEventMulticaster()
                .multicastEvent(earlyEvent);
        }
    }
}

this.finishBeanFactoryInitialization(beanFactory)方法将所有单实例bean创建。

finishRefresh()完成BeanFactory的初始化创建工作,ioc容器创建完成。

protected void finishRefresh()
{
    //清除环境级别的缓存
    this.clearResourceCaches();
    //初始化与生命周期有关的后置处理
    this.initLifecycleProcessor();
    //拿到上面定义的生命周期处理器,回调onRefresh
    this.getLifecycleProcessor()
        .onRefresh();
    //发布容器刷新完成容器时间
    this.publishEvent((ApplicationEvent)(new ContextRefreshedEvent(this)));
    //暴露一些 Mbean类
    LiveBeansView.registerApplicationContext(this);
}

此文源于网络,仅供参考,假如你还想了解更多的java编程常见问题,可以继续的通过关注赋能网来进行相关内容的获取哦。


发表评论
0评