Spring源码解析-applicationContext

  • Demo
  • uml类图
    • ApplicationContext
    • ApplicationListener
  • 源码解析
    • 主流程
    • obtainFreshBeanFactory
    • prepareBeanFactory
    • invokeBeanFactoryPostProcessors
    • registerBeanPostProcessors
    • registerListeners
    • finishRefresh
  • 总结

在已经有BeanFactory可以完成Ioc功能情况下,spring又提供了ApplicationContext,why?可以简单理解BeanFactory为可用,ApplicationContext封装了Beanfactory,提供了上下文、国际化、监听等更多的可选功能,让其能用,使用时,优先使用ApplicationContext。

Demo

跟beanfactory的demo唯一不同的就是:

//BeanFactory ctx = new XmlBeanFactory(new ClassPathResource("spring.xml"));

ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");

uml类图

ApplicationContext

ApplicationListener

源码解析

主流程

//ClassPathXmlApplicationContext
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException {
    this(configLocations, refresh, null);
}

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
        throws BeansException {

    super(parent);
    // 设置configLocations
    setConfigLocations(configLocations);
    if (refresh) {
        refresh();
    }
}

//AbstractApplicationContext
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // 设置和校验系统变量和环境变量的值
        prepareRefresh();

        // 获取beanFactory
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

        // 配置BeanFactory上下文
        prepareBeanFactory(beanFactory);

        try {
            // 子类扩展,beanFactory的后置处理
            postProcessBeanFactory(beanFactory);

            // 调用BeanFactory的后置处理器
            invokeBeanFactoryPostProcessors(beanFactory);

            // 注册bean processors,只是注册,bean创建时调用.
            registerBeanPostProcessors(beanFactory);

            // 国际化
            initMessageSource();

            // 初始化监听的Multicaster,有自定义就是用自定义,没有就使用默认SimpleApplicationEventMulticaster
            initApplicationEventMulticaster();

            // 子类扩展
            onRefresh();

            // 注册listen
            registerListeners();

            // 实例化所有非延迟加载的bean,相当于循环调用getbean
            finishBeanFactoryInitialization(beanFactory);

            // 完成刷新,通知LifecycleProcessor,ContextRefreshedEvent事件(这个很有用,可以监听这个事件)
            finishRefresh();
        }

        catch (BeansException ex) {
            // Destroy already created singletons to avoid dangling resources.
            destroyBeans();

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

            // Propagate exception to caller.
            throw ex;
        }
    }
}

整个refresh过程,流程清晰,从spring学了这一招。

obtainFreshBeanFactory

这个流程里面有个需要注意的地方:

//AbstractRefreshableApplicationContext
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
    if (this.allowBeanDefinitionOverriding != null) {
        beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
    }
    if (this.allowCircularReferences != null) {
        beanFactory.setAllowCircularReferences(this.allowCircularReferences);
    }
    // 用于@Autowire和@Qualifier,没试过,TODO
    beanFactory.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
}

prepareBeanFactory

//ClassPathXmlApplicationContext
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // Tell the internal bean factory to use the context‘s class loader etc.
    beanFactory.setBeanClassLoader(getClassLoader()); // 之前beanfactory没有设置classLoader
    beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver()); // el表达式
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, this.getEnvironment())); // 配置属性注入编辑器

    //ApplicationContextAwareProcessor这个beanpostprocessor,在实例化前postProcessBeforeInitialization设置下面忽略的依赖
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
    beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
    beanFactory.ignoreDependencyInterface(EnvironmentAware.class);

    // 设置几个自动注册的依赖,注入的时候直接用
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);

    // aop类加载期织入支持Detect a LoadTimeWeaver and prepare for weaving, if found.
    if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        // Set a temporary ClassLoader for type matching.
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }

    // // 注册一些默认bean,方便使用
    if (!beanFactory.containsBean(ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
    }

    if (!beanFactory.containsBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
    }

    if (!beanFactory.containsBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
    }
}

invokeBeanFactoryPostProcessors

//AbstractApplicationContext
//BeanFactoryPostProcessor激活调用
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    // Invoke BeanDefinitionRegistryPostProcessors first, if any.
    Set<String> processedBeans = new HashSet<String>();
    //BeanDefinitionRegistry中的BeanPostProcessor
    if (beanFactory instanceof BeanDefinitionRegistry) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
        List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
                new LinkedList<BeanDefinitionRegistryPostProcessor>();
        //硬编码进来的
        for (BeanFactoryPostProcessor postProcessor : getBeanFactoryPostProcessors()) {
            if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                //BeanDefinitionRegistryPostProcessor继承了BeanFactoryPostProcessor,多了个调用postProcessBeanDefinitionRegistry,这里区分下
                BeanDefinitionRegistryPostProcessor registryPostProcessor =
                        (BeanDefinitionRegistryPostProcessor) postProcessor;
                registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
                registryPostProcessors.add(registryPostProcessor);
            }
            else {
                regularPostProcessors.add(postProcessor);
            }
        }
        //配置的bean中获取
        Map<String, BeanDefinitionRegistryPostProcessor> beanMap =
                beanFactory.getBeansOfType(BeanDefinitionRegistryPostProcessor.class, true, false);
        List<BeanDefinitionRegistryPostProcessor> registryPostProcessorBeans =
                new ArrayList<BeanDefinitionRegistryPostProcessor>(beanMap.values());
        OrderComparator.sort(registryPostProcessorBeans);
        for (BeanDefinitionRegistryPostProcessor postProcessor : registryPostProcessorBeans) {
            //调用postProcessBeanDefinitionRegistry
            postProcessor.postProcessBeanDefinitionRegistry(registry);
        }
        //调用postProcessBeanFactory
        invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(registryPostProcessorBeans, beanFactory);
        invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
        // processedBeans包含所有处理过的
        processedBeans.addAll(beanMap.keySet());
    }
    else {
        // Invoke factory processors registered with the context instance.
        invokeBeanFactoryPostProcessors(getBeanFactoryPostProcessors(), beanFactory);
    }

    // beanFactory中获取BeanFactoryPostProcessor
    String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

    // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
    List<String> orderedPostProcessorNames = new ArrayList<String>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
    for (String ppName : postProcessorNames) {
        // 按照PriorityOrdered\Ordered\其他区分下,如果已经处理过,会过滤掉,不会重复处理
        if (processedBeans.contains(ppName)) {
            // skip - already processed in first phase above
        }
        else if (isTypeMatch(ppName, PriorityOrdered.class)) {
            priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
        }
        else if (isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        }
        else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }
    // 对分类过的排序然后调用
    // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
    OrderComparator.sort(priorityOrderedPostProcessors);
    invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

    // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
    List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
    for (String postProcessorName : orderedPostProcessorNames) {
        orderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    OrderComparator.sort(orderedPostProcessors);
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

    // Finally, invoke all other BeanFactoryPostProcessors.
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
    for (String postProcessorName : nonOrderedPostProcessorNames) {
        nonOrderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
}

registerBeanPostProcessors

//AbstractApplicationContext
//注册所有的BeanPostProcessor,只注册,不调用
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

    // 注册BeanPostProcessorChecker,只是info日志表明bean没有被所有processor处理,没感觉想干嘛
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

    // 按照实现PriorityOrdered,Ordered,其他.分类排序注册到beanfactory
    List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
    List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
    List<String> orderedPostProcessorNames = new ArrayList<String>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
    for (String ppName : postProcessorNames) {
        if (isTypeMatch(ppName, PriorityOrdered.class)) {
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            priorityOrderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
        else if (isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        }
        else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }

    // First, register the BeanPostProcessors that implement PriorityOrdered.
    OrderComparator.sort(priorityOrderedPostProcessors);
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

    // Next, register the BeanPostProcessors that implement Ordered.
    List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
    for (String ppName : orderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        orderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    OrderComparator.sort(orderedPostProcessors);
    registerBeanPostProcessors(beanFactory, orderedPostProcessors);

    // Now, register all regular BeanPostProcessors.
    List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
    for (String ppName : nonOrderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        nonOrderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

    // Finally, re-register all internal BeanPostProcessors.
    OrderComparator.sort(internalPostProcessors);
    registerBeanPostProcessors(beanFactory, internalPostProcessors);
    //ApplicationListenerDetector初始化后,如果是listener,添加到监听里面
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector());
}

//注册所有的BeanPostProcessor到Beanfactory
private void registerBeanPostProcessors(
        ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

    for (BeanPostProcessor postProcessor : postProcessors) {
        beanFactory.addBeanPostProcessor(postProcessor);
    }
}

只注册,不调用,跟beanfactoryprocessor不一样。

registerListeners

//AbstractApplicationContext
protected void registerListeners() {
    // 注册硬编码的listener
    for (ApplicationListener<?> listener : getApplicationListeners()) {
        getApplicationEventMulticaster().addApplicationListener(listener);
    }
    // 注册xml配置的listener
    String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
    for (String lisName : listenerBeanNames) {
        getApplicationEventMulticaster().addApplicationListenerBean(lisName);
    }
}

finishRefresh

//AbstractApplicationContext
protected void finishRefresh() {
    // 初始化LifecycleProcessor,有自定义就使用自定义的,没有就使用DefaultLifecycleProcessor(onRefresh和onClose)
    initLifecycleProcessor();

    // 广播onRefresh 给所有实现lifeProcessor
    getLifecycleProcessor().onRefresh();

    // Publish ContextRefreshedEvent事件
    publishEvent(new ContextRefreshedEvent(this));
}

可以通过监听ContextRefreshedEvent事件,在所有applicationContext完成所有操作后修改bean,做其他操作。

总结

  1. 对比Beanfactory优先使用ApplicationContext;
  2. ContextRefreshedEvent监听的扩展;
  3. 整个加载处理提炼的很清晰,而且很多地方留下了扩展点,看起来舒服。
时间: 2024-10-12 13:26:43

Spring源码解析-applicationContext的相关文章

Spring源码解析-applicationContext.xml加载和bean的注册

applicationContext文件加载和bean注册流程? Spring对于从事Java开发的boy来说,再熟悉不过了,对于我们这个牛逼的框架的介绍就不在这里复述了,Spring这个大杂烩,怎么去使用怎么去配置,各种百度谷歌都能查到很多大牛教程,但是,当我们按着教程一步步的把spring的开发框架搭建起来的时候,有没有一种想搞明白spring的冲动,万事开头难,就要从开头开始,而我认为spring开头就是如何加载配置文件,并初始化配置文件里面的bean当然也包括了我们用注解Service.

Spring 源码解析之HandlerAdapter源码解析(二)

Spring 源码解析之HandlerAdapter源码解析(二) 前言 看这篇之前需要有Spring 源码解析之HandlerMapping源码解析(一)这篇的基础,这篇主要是把请求流程中的调用controller流程单独拿出来了 解决上篇文章遗留的问题 getHandler(processedRequest) 这个方法是如何查找到对应处理的HandlerExecutionChain和HandlerMapping的,比如说静态资源的处理和请求的处理肯定是不同的HandlerMapping ge

软件开发工程师(JAVA)中级考试大纲--spring源码解析

spring源码解析(1)----IOC 一.IOC容器 在Spring中,IOC容器的重要地位我们就不多说了,对于Spring的使用者而言,IOC容器实际上是什么呢?我们可以说BeanFactory就是我们看到的IoC容器,当然了Spring为我们准备了许多种IoC容器来使用,这样可以方便我们从不同的层面,不同的资源位置,不同的形式的定义信息来建立我们需要的IoC容器. 在Spring中,最基本的IOC容器接口是BeanFactory - 这个接口为具体的IOC容器的实现作了最基本的功能规定 

Spring 源码解析之DispatcherServlet源码解析(五)

Spring 源码解析之DispatcherServlet源码解析(五) 前言 本文需要有前四篇文章的基础,才能够清晰易懂,有兴趣可以先看看详细的流程,这篇文章可以说是第一篇文章,也可以说是前四篇文章的的汇总,Spring的整个请求流程都是围绕着DispatcherServlet进行的 类结构图 根据类的结构来说DispatcherServlet本身也是继承了HttpServlet的,所有的请求都是根据这一个Servlet来进行转发的,同时解释了为什么需要在web.xml进行如下配置,因为Spr

SPRING源码解析-SPRING 核心-IOC

IoC 和 AOP是Spring的核心, 是Spring系统中其他组件模块和应用开发的基础.透过这两个模块的设计和实现可以了解Spring倡导的对企业应用开发所应秉承的思路: 易用性. POJO开发企业应用, 直接依赖于Java语言,而不是容器和框架. 提升程序的可测试性,提高软件质量. 提供一致性编程模型,面向接口的编程 降低应用的负载和框架的侵入性.IoC和AOP实现. 不作为现有解决方案的替代,而是集成现有. IoC和AOP这两个核心组件,特别是IoC容器,使用户在使用Spring完成PO

Spring 源码解析之ViewResolver源码解析(四)

Spring 源码解析之ViewResolver源码解析(四) 1 ViewResolver类功能解析 1.1 ViewResolver Interface to be implemented by objects that can resolve views by name. View state doesn't change during the running of the application, so implementations are free to cache views. I

Spring源码解析和配置文件加载

Spring类的继承结构图: Spring运用了大量的模板方法模式和策略模式,所以各位看源码的时候,务必留意,每一个继承的层次都有不同的作用,然后将相同的地方抽取出来,依赖抽象将不同的处理按照不同的策略去处理. 步骤A. 读取 Resource 文件形成 Document 模型  类图: XmlBeanFactory -> XmlBeanDefinitionReader Spring 使用 XmlBeanDefinitionReader 来读取并解析 xml 文件,XmlBeanDefiniti

Spring源码解析——start from BeanFactory(一)

先来看一下我们学习Spring时候的ABC代码: BeanFactory beanFactory=new ClassPathXmlApplicationContext("applicationContext.xml"); UserManager userManager=(UserManager)beanFactory.getBean("UserManagerImpl"); userManager.add("dd","d");

spring源码解析之IOC容器(一)

学习优秀框架的源码,是提升个人技术水平必不可少的一个环节.如果只是停留在知道怎么用,但是不懂其中的来龙去脉,在技术的道路上注定走不长远.最近,学习了一段时间的spring源码,现在整理出来,以便日后温故知新. IOC容器是spring最核心的模块之一,是整个spring体系的基石,spring其他模块中,都需要用到IOC容器的功能.spring框架为我们提供了多种IOC容器,DefaultableBeanFact ory.FileSystemXmlApplicationContext.Class