spring container 初始化概览

Spring BeanDefinition

spring容器托管的对象即是一个个BeanDefinition,其类的层次结构如图所示:


spring container 初始化概览_第1张图片
BeanDefinition的抽象层次结构.png

@Import引入的class在解析的时候对应AnnotatedGenericBeanDefinition
BeanMethod(@Bean)解析的时候对应ConfigurationClassBeanDefinition
ApplicationContext作为spring central interfacae, 提供以下功能:

  1. Bean factory methods for accessing application components. 继承ListableBeanFactory接口
  2. 加载资源文件,继承ResourceLoader接口
  3. 向注册的listener发布事件,继承ApplicationEventPublisher接口
  4. 解析message source,支持国际化,继承MessageSource接口

Spring ApplicationContext 简略层次结构如图所示:


spring container 初始化概览_第2张图片
applicationContext 粗略类图.png

spring boot 启动时代码片段

public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    FailureAnalyzers analyzers = null;
    configureHeadlessProperty();
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.starting();
    try {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        ConfigurableEnvironment environment = prepareEnvironment(listener,applicationArguments);
        Banner printedBanner = printBanner(environment);
        context = createApplicationContext();//创建上下文
        analyzers = new FailureAnalyzers(context);
        prepareContext(context, environment, listeners, applicationArguments,printedBanner);
        refreshContext(context);//刷新上下文
        afterRefresh(context, applicationArguments);
        listeners.finished(context, null);
        stopWatch.stop();
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
        }
        return context;
        
    }catch (Throwable ex) {
        handleRunFailure(context, listeners, analyzers,ex);
        throw new IllegalStateException(ex);
    }
}
创建上下文:
注册BeanFactoryPostProcessor、BeanPostProcessor

创建上下文如果是在web环境上下文类型为:AnnotationConfigEmbeddedWebApplicationContext;否则为默认实现AnnotationConfigApplicationContext

protected ConfigurableApplicationContext createApplicationContext() {
    Class contextClass = this.applicationContextClass;
    if (contextClass == null) {
        try {
            contextClass = Class.forName(this.webEnvironment ? DEFAULT_WEB_CONTEXT_CLASS : DEFAULT_CONTEXT_CLASS);
        } catch (ClassNotFoundException ex) {
            throw new IllegalStateException("Unable create a default ApplicationContext,  please specify an ApplicationContextClass",ex);
        }
    }
    return (ConfigurableApplicationContext) BeanUtils.instantiate(contextClass);
}

实例化contextClass时,向BeanFactory注册BeanFactoryPostProcessor,以及BeanPostProcessor;

ConfigurationClassPostProcessor(处理@Configuration注解)
AutowiredAnnotationBeanPostProcessor(处理@Autowire,@Inject,@Value注解)
RequiredAnnotationBeanPostProcessor(处理@Requried注解)
CommonAnnotationBeanPostProcessor(处理 @Resource注解)

AnnotationConfigUtils 代码片段
public static Set registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, Object source) {
    …
    Set beanDefs = new LinkedHashSet(4);

    if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
    }

    if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    }

    if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    }

    // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
    if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
        RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
        def.setSource(source);
        beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
    }
    …
    return beanDefs;
}

刷新上下文:

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

  设置开始时间,active,closed标志位,以及初始化Property Resource

prepareBeanFactory

  配置BeanFactory的标准上下文特征,注册BeanPostProcessor等
StandardBeanExpressionResolver(解析SPEL表达式),ApplicationContextAwareProcessor(BeanPostProcessor)

postProcessBeanFactory

  扩展方法,可用于注册beanDefinition
比如:AnnotationConfigEmbeddedWebApplicationContext

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    super.postProcessBeanFactory(beanFactory);
    if (this.basePackages != null && this.basePackages.length > 0) {
        this.scanner.scan(this.basePackages); 
    }
    if (this.annotatedClasses != null && this.annotatedClasses.length > 0) {
        this.reader.register(this.annotatedClasses);
    }
}
invokeBeanFactoryPostProcessors

BeanFactoryPostProcessor部分类层次结构


spring container 初始化概览_第3张图片

调用过程:

  1. 优先调用BeanDefinitionRegistryPostProcessor,处理顺序如图所示:
    First: 调用实现PriorityOrdered接口,ex:ConfigurationClassPostProcessor
    Second: 调用实现Ordered接口
    Third: 调用普通类型

              
    spring container 初始化概览_第4张图片
  2. 再者调用实现BeanFactoryPostProcessor接口的类
    First: 调用实现PriorityOrdered接口
    Second: 调用实现Ordered接口
    Third: 调用普通类型


    spring container 初始化概览_第5张图片
registerBeanPostProcessors

  注册BeanPostProcessors至BeanFactory,在创建Bean时调用

initMessageSource

  初始化Message Resource

initApplicationEventMulticaster

  初始化ApplicationEventMulticaster

onRefresh

  模板方法,子类可重载

registerListeners

  注册实现了ApplicationListener接口的listener

finishBeanFactoryInitialization

  初始化BeanFactory里的Bean,懒加载Bean在此处不会初始化

finishRefresh

  调用LifecycleProcessor的onRefresh,发布ContextRefreshedEvent事件

你可能感兴趣的:(spring container 初始化概览)