6、spring容器创建过程(注解)

  • 这一节的内容主要是探索spring的容器创建过程,这个过程非常的复杂,包含了容器的创建、bean的加载-创建-注册-初始化、以及其他组件的注册等等过程。但是好在spring对整个过程封装逻辑比较清晰,可以通过源码一步一步的解读。

1、准备阶段

  • 为了能进行debug进行源码解读,需要创建一个简单的测试环境,然后对其中加载配置文件并创建容器那一行打一个断点。
//创建一个注解形式的配置类
@Configuration//标记这个类为注解类==配置文件
public class UserConfig {
    @Bean
    public User user() {
        return new User();
    }
}
//测试
public class Test {
    public static void main(String[] args) {
//加载配置文件并创建容器
        ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(UserConfig.class);
        User user = (User) context.getBean("user");
        System.out.println(user);
    }
}
  • 创建AnnotationConfigApplicationContext
    public AnnotationConfigApplicationContext(Class... annotatedClasses) {
//创建AnnotationConfigApplicationContextbin初始化相关信息类
        this();
//注册多个注解Bean定义类  
        register(annotatedClasses);
//刷新容器
        refresh();
    }

二、this()方法

  • 主要完成创建注解bean解析器和类路径bean定义扫描器的创建,并设置到容器中
  //创建一个读取注解的Bean定义读取器,并将其设置到容器中 
private final AnnotatedBeanDefinitionReader reader;
//创建一个扫描指定类路径中注解Bean定义的扫描器,并将其设置到容器中 
private final ClassPathBeanDefinitionScanner scanner;
public AnnotationConfigApplicationContext() {
    1.....  this.reader = new AnnotatedBeanDefinitionReader(this);
    2.....  this.scanner = new ClassPathBeanDefinitionScanner(this);
    }
(1)1所处的行最终会执行
    public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
        Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
        Assert.notNull(environment, "Environment must not be null");
//interface for registries that hold bean definitions
        this.registry = registry;
//Internal class used to evaluate {@link Conditional} annotations.
        this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
    AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
    }
(2)2所处的行最终会执行
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment) {
        super(useDefaultFilters, environment);

        Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
        this.registry = registry;

        // Determine ResourceLoader to use.
        if (this.registry instanceof ResourceLoader) {
            setResourceLoader((ResourceLoader) this.registry);
        }
    }

3、register(annotatedClasses)方法

  • 主要利用AnnotatedBeanDefinitionReader对注解bean进行解析并进行注册
1、AnnotationConfigApplicationContext.register
public void register(Class... annotatedClasses) {
        Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
        this.reader.register(annotatedClasses);
    }
2、AnnotatedBeanDefinitionReader.register
public void register(Class... annotatedClasses) {
        for (Class annotatedClass : annotatedClasses) {
            registerBean(annotatedClass);
        }
    }
3、AnnotatedBeanDefinitionReader.registerBean
public void registerBean(Class annotatedClass, String name,
            @SuppressWarnings("unchecked") Class... qualifiers) {
//该类继承GenericBeanDefinition并实现AnnotatedBeanDefinition,
//AnnotatedGenericBeanDefinition 描述了一个注解bean实例,它具有属性值,构造函数参数值。
        AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
//根据{@code @Conditional}注释确定是否应跳过某个项目
        if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
            return;
        }
//ScopeMetadata 描述了一个Spring管理的bean,包括范围名称和范围的代理行为范围的特点。(也就是spring的作用域)
        ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
        abd.setScope(scopeMetadata.getScopeName());
//获取传入注解配置类的bean
        String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
//处理该注解bean上的一些其他注解属性,比如@lazy,@Primary等注解
//有的话加入到AnnotatedGenericBeanDefinition 中
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
//@qualifiers注解
        if (qualifiers != null) {
            for (Class qualifier : qualifiers) {
                if (Primary.class == qualifier) {
                    abd.setPrimary(true);
                }
                else if (Lazy.class == qualifier) {
                    abd.setLazyInit(true);
                }
                else {
                    abd.addQualifier(new AutowireCandidateQualifier(qualifier));
                }
            }
        }
//BeanDefinitionHolder拥有名称和别名的BeanDefinition的持有者。可以注册为内部bean的占位符。
        BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
        definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
//在BeanDefinitionRegistry中注册相应的获取的bean,definitionHolder.getBeanName()作为beanName
//definitionHolder.getBeanDefinition()作为value,如果有别名还要进行别名注册
    BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
    }

四、refresh方法

  • 这个是容器创建过程中最重要的方法
public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // 1、prepareRefresh()刷新前的预处理.
            prepareRefresh();

            // 2、获取BeanFactory.
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            //3、BeanFactory的预准备工作(BeanFactory进行一些设置).
            prepareBeanFactory(beanFactory);

            try {
                // 4、BeanFactory准备工作完成后进行的后置处理工作
                postProcessBeanFactory(beanFactory);
======================以上是BeanFactory的创建及预准备工作===============
                // 5、执行BeanFactoryPostProcessor的方法
                invokeBeanFactoryPostProcessors(beanFactory);

                //6、注册BeanPostProcessor(Bean的后置处理器)
                registerBeanPostProcessors(beanFactory);

                // 7、初始化MessageSource组件(做国际化功能;消息绑定,消息解析);
                initMessageSource();

                //8、初始化事件派发器;
                initApplicationEventMulticaster();

                // 9、在子容器(子类)初初始化特殊的bean
                onRefresh();

                // 10、给容器中将所有项目里面的ApplicationListener注册进来.
                registerListeners();

                // 11、初始化所有剩下的单实例bean;
                finishBeanFactoryInitialization(beanFactory);

                // 12、完成BeanFactory的初始化创建工作;IOC容器就创建完成;
                finishRefresh();
            }

1、prepareRefresh刷新前的预处理

  • 完成容器刷新前的准备工作,设置其启动日期和活动标志以及执行属性源的任何初始化。
protected void prepareRefresh() {
        this.startupDate = System.currentTimeMillis();
        this.closed.set(false);
        this.active.set(true);

        if (logger.isInfoEnabled()) {
            logger.info("Refreshing " + this);
        }
        //1、初始化一些属性设置(抽象方法,子类自定义个性化的属性设置方法)
        initPropertySources();
        //2、 检验属性的合法等
        getEnvironment().validateRequiredProperties();
        // 3、保存容器中的一些早期的事件
        this.earlyApplicationEvents = new LinkedHashSet();
    }

3、obtainFreshBeanFactory获取BeanFactory

GenericApplicationContext
//1、告诉子类刷新内部bean工厂
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//(1)刷新【创建】BeanFactory,并设置序列id,其中this.beanFactory为
//DefaultListableBeanFactory,这个beanfactory创建过程是在上面介绍的this方法中执行的,
//因为AnnotatedBeanDefinitionReader继承GenericApplicationContext类
        refreshBeanFactory();
//返回刚才DefaultListableBeanFactory对象
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (logger.isDebugEnabled()) {
            logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
        }
        return beanFactory;
    }

3、prepareBeanFactoryBeanFactory的预准备工作

//配置工厂的标准上下文特征,例如上下文的ClassLoader和后处理器
    protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        // 1、设置BeanFactory的类加载器、支持表达式解析器...
        beanFactory.setBeanClassLoader(getClassLoader());
        beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
        beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

//2、 添加部分BeanPostProcessor【例如ApplicationContextAwareProcessor】
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//3、设置忽略的自动装配的接口EnvironmentAware、EmbeddedValueResolverAware、xxx;
    beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
        beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
        beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
        beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
        beanFactory.ignoreDependencyInterface(EnvironmentAware.class);

//4、注册可以解析的自动装配;我们能直接在任何组件中自动注入:BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
        beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
        beanFactory.registerResolvableDependency(ResourceLoader.class, this);
        beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
        beanFactory.registerResolvableDependency(ApplicationContext.class, this);

        // 5、添加编译时的AspectJ;
        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()));
        }

        // 6、给BeanFactory中注册一些能用的组件:environment【ConfigurableEnvironment】、
        //systemProperties【Map】、systemEnvironment【Map】
        if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
            beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
        }
        if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
            beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
        }
        if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
            beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
        }
    }

4、postProcessBeanFactory完成后置处理工作

//子类通过重写这个方法来在BeanFactory创建并预准备完成以后做进一步的设置
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    }

5、执行BeanFactoryPostProcessor的方法

  • 实例化并调用所有已注册的BeanFactoryPostProcessor bean,如果给定,则遵循显式顺序。必须在单例实例化之前调用
  • BeanFactoryPostProcessor:BeanFactory的后置处理器。在BeanFactory标准初始化之后执行的
1、AbstractApplicationContext.invokeBeanFactoryPostProcessors
    protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//执行invokeBeanFactoryPostProcessors方法
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

        // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
        // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
        if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
            beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
            beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
        }
    }
2、PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors
public static void invokeBeanFactoryPostProcessors(
            ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors) {

        // Invoke BeanDefinitionRegistryPostProcessors first, if any.
        Set processedBeans = new HashSet();

        if (beanFactory instanceof BeanDefinitionRegistry) {
            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
            List regularPostProcessors = new LinkedList();
            List registryPostProcessors =
                    new LinkedList();

            for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
                if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                    BeanDefinitionRegistryPostProcessor registryPostProcessor =
                            (BeanDefinitionRegistryPostProcessor) postProcessor;
                    registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
                    registryPostProcessors.add(registryPostProcessor);
                }
                else {
                    regularPostProcessors.add(postProcessor);
                }
            }
===============先执行BeanDefinitionRegistryPostProcessor接口============
//1、获取所有的实现该BeanDefinitionRegistryPostProcessor的名称
            String[] postProcessorNames =
                    beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

//2、看先执行实现了PriorityOrdered优先级接口的BeanDefinitionRegistryPostProcessor
            List priorityOrderedPostProcessors = new ArrayList();
            for (String ppName : postProcessorNames) {
                if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                    priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                }
            }
            sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
            registryPostProcessors.addAll(priorityOrderedPostProcessors);
            invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);

//3、在执行实现了Ordered顺序接口的BeanDefinitionRegistryPostProcessor
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            List orderedPostProcessors = new ArrayList();
            for (String ppName : postProcessorNames) {
                if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                    orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                }
            }
            sortPostProcessors(beanFactory, orderedPostProcessors);
            registryPostProcessors.addAll(orderedPostProcessors);
            invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);

//4、最后执行没有实现任何优先级或者是顺序接口的BeanDefinitionRegistryPostProcessors;
            boolean reiterate = true;
            while (reiterate) {
                reiterate = false;
                postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
                for (String ppName : postProcessorNames) {
                    if (!processedBeans.contains(ppName)) {
                        BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);
                        registryPostProcessors.add(pp);
                        processedBeans.add(ppName);
                        pp.postProcessBeanDefinitionRegistry(registry);
                        reiterate = true;
                    }
                }
            }

            // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
            invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
            invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
        }

        else {
            // Invoke factory processors registered with the context instance.
            invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
        }

============再执行BeanFactoryPostProcessor接口的方法==============
//1、获取所有的BeanFactoryPostProcessor
        String[] postProcessorNames =
                beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);


        List priorityOrderedPostProcessors = new ArrayList();
        List orderedPostProcessorNames = new ArrayList();
        List nonOrderedPostProcessorNames = new ArrayList();
        for (String ppName : postProcessorNames) {
            if (processedBeans.contains(ppName)) {
                // skip - already processed in first phase above
            }
            else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
            }
            else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
                orderedPostProcessorNames.add(ppName);
            }
            else {
                nonOrderedPostProcessorNames.add(ppName);
            }
        }

//2、看先执行实现了PriorityOrdered优先级接口的
        sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
        invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

//3、在执行实现了Ordered顺序接口的BeanFactoryPostProcessor
        List orderedPostProcessors = new ArrayList();
        for (String postProcessorName : orderedPostProcessorNames) {
            orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
        }
        sortPostProcessors(beanFactory, orderedPostProcessors);
        invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

//4、最后执行没有实现任何优先级或者是顺序接口的BeanFactoryPostProcessor
        List nonOrderedPostProcessors = new ArrayList();
        for (String postProcessorName : nonOrderedPostProcessorNames) {
            nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
        }
        invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

        // Clear cached merged bean definitions since the post-processors might have
        // modified the original metadata, e.g. replacing placeholders in values...
        beanFactory.clearMetadataCache();
    }

6、注册BeanPostProcessor(Bean的后置处理器)

  • 不同接口类型的BeanPostProcessor;在Bean创建前后的执行时机是不一样的,有BeanPostProcessor、InstantiationAwareBeanPostProcessor、等
public static void registerBeanPostProcessors(
            ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
//1、获取所有的 BeanPostProcessor(其实后置处理器都默认可以通过PriorityOrdered、Ordered接口来执行优先级)
        String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

        // Register BeanPostProcessorChecker that logs an info message when
        // a bean is created during BeanPostProcessor instantiation, i.e. when
        // a bean is not eligible for getting processed by all BeanPostProcessors.
        int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
        beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));


        List priorityOrderedPostProcessors = new ArrayList();
        List internalPostProcessors = new ArrayList();
        List orderedPostProcessorNames = new ArrayList();
        List nonOrderedPostProcessorNames = new ArrayList();
        for (String ppName : postProcessorNames) {
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
                priorityOrderedPostProcessors.add(pp);
                if (pp instanceof MergedBeanDefinitionPostProcessor) {
                    internalPostProcessors.add(pp);
                }
            }
            else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
                orderedPostProcessorNames.add(ppName);
            }
            else {
                nonOrderedPostProcessorNames.add(ppName);
            }
        }

//2、先注册PriorityOrdered优先级接口的BeanPostProcessor
        sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
        registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

//3、再注册Ordered接口的
        List orderedPostProcessors = new ArrayList();
        for (String ppName : orderedPostProcessorNames) {
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            orderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
        sortPostProcessors(beanFactory, orderedPostProcessors);
        registerBeanPostProcessors(beanFactory, orderedPostProcessors);

//4、最后注册没有实现任何优先级接口的
        List nonOrderedPostProcessors = new ArrayList();
        for (String ppName : nonOrderedPostProcessorNames) {
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            nonOrderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
        registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
//5、最终注册 internal BeanPostProcessors.(比如MergedBeanDefinitionPostProcessor)
        sortPostProcessors(beanFactory, internalPostProcessors);
ApplicationListenerDetector
        registerBeanPostProcessors(beanFactory, internalPostProcessors);
//6、在Bean创建完成后检查是否是ApplicationListener,如果是注册一个
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    }

7、初始化MessageSource组件(做国际化功能;消息绑定,消息解析)

protected void initMessageSource() {
//1、获取BeanFactory
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//2、看容器中是否有id为messageSource的,类型是MessageSource的组件,如果有赋值给messageSource,如果没有自己创建一个DelegatingMessageSource
        if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
            this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
            // Make MessageSource aware of parent MessageSource.
            if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
                HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
                if (hms.getParentMessageSource() == null) {
                    // Only set parent context as parent MessageSource if no parent MessageSource
                    // registered already.
                    hms.setParentMessageSource(getInternalParentMessageSource());
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Using MessageSource [" + this.messageSource + "]");
            }
        }
        else {
            // Use empty MessageSource to be able to accept getMessage calls.
            DelegatingMessageSource dms = new DelegatingMessageSource();
            dms.setParentMessageSource(getInternalParentMessageSource());
            this.messageSource = dms;
//3、把创建好的MessageSource注册在容器中,以后获取国际化配置文件的值的时候,可以自动注入MessageSource;          beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
            if (logger.isDebugEnabled()) {
                logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
                        "': using default [" + this.messageSource + "]");
            }
        }
    }

8、初始化事件派发器

    protected void initApplicationEventMulticaster() {
//1、获取BeanFactory
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//2、从BeanFactory中获取applicationEventMulticaster的ApplicationEventMulticaster;
        if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
            this.applicationEventMulticaster =
                    beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
            if (logger.isDebugEnabled()) {
                logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
            }
        }
        else {
//3、如果上一步没有配置;创建一个SimpleApplicationEventMulticaster
            this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
//4、将创建的ApplicationEventMulticaster添加到BeanFactory中,以后其他组件直接自动注入         beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
            if (logger.isDebugEnabled()) {
                logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
                        APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
                        "': using default [" + this.applicationEventMulticaster + "]");
            }
        }
    }

9、onRefresh在子容器(子类)初初始化特殊的bean

  • 子类重写这个方法,在容器刷新的时候可以自定义逻辑

10、给容器中将所有项目里面的ApplicationListener注册进来

protected void registerListeners() {
//首先在事件派发器中注册静态指定的事件监听器
        for (ApplicationListener listener : getApplicationListeners()) {
    getApplicationEventMulticaster().addApplicationListener(listener);
        }
//1、从容器中拿到所有的ApplicationListener并遍历
        String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
        for (String listenerBeanName : listenerBeanNames) {
//2、将每个监听器添加到事件派发器中             getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
        }

//3、派发之前步骤产生的事件;
        Set earlyEventsToProcess = this.earlyApplicationEvents;
        this.earlyApplicationEvents = null;
        if (earlyEventsToProcess != null) {
            for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
                getApplicationEventMulticaster().multicastEvent(earlyEvent);
            }
        }
    }

11、初始化所有剩下的单实例bean

  • 重点在方法preInstantiateSingletons初始化后剩下的单实例bean
public void preInstantiateSingletons() throws BeansException {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Pre-instantiating singletons in " + this);
        }

//1、获取容器中的所有Bean,依次进行初始化和创建对象
        List beanNames = new ArrayList(this.beanDefinitionNames);

        // Trigger initialization of all non-lazy singleton beans...
        for (String beanName : beanNames) {
//2、获取Bean的定义信息;RootBeanDefinition
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//3、Bean不是抽象的,是单实例的,是懒加载;
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//3.1判断是否是FactoryBean;是否是实现FactoryBean接口的Bean
                if (isFactoryBean(beanName)) {
                    final FactoryBean factory = (FactoryBean) getBean(FACTORY_BEAN_PREFIX + beanName);
                    boolean isEagerInit;
                    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                        isEagerInit = AccessController.doPrivileged(new PrivilegedAction() {
                            @Override
                            public Boolean run() {
                                return ((SmartFactoryBean) factory).isEagerInit();
                            }
                        }, getAccessControlContext());
                    }
                    else {
                        isEagerInit = (factory instanceof SmartFactoryBean &&
                                ((SmartFactoryBean) factory).isEagerInit());
                    }
                    if (isEagerInit) {
                        getBean(beanName);
                    }
                }
                else {
//3.2不是工厂Bean。利用getBean(beanName);创建对象
                    getBean(beanName);
                }
            }
        }

        // Trigger post-initialization callback for all applicable beans...
        for (String beanName : beanNames) {
            Object singletonInstance = getSingleton(beanName);
//4.检查所有的Bean是否是SmartInitializingSingleton接口的;如果是;就执行afterSingletonsInstantiated();
            if (singletonInstance instanceof SmartInitializingSingleton) {
                final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction() {
                        @Override
                        public Object run() {
                            smartSingleton.afterSingletonsInstantiated();
                            return null;
                        }
                    }, getAccessControlContext());
                }
                else {
                    smartSingleton.afterSingletonsInstantiated();
                }
            }
        }
    }
 
 
  • getBean(beanName)创建对象
//AbstractBeanFactory.doGetBean
protected  T doGetBean(
            final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly)
            throws BeansException {

        final String beanName = transformedBeanName(name);
        Object bean;

//1、先获取缓存中保存的单实例Bean。如果能获取到说明这个Bean之前被创建过(所有创建过的单实例
//Bean都会被缓存起来)从private final Map singletonObjects = new ConcurrentHashMap(256);获取的
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            if (logger.isDebugEnabled()) {
                if (isSingletonCurrentlyInCreation(beanName)) {
                    logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
                            "' that is not fully initialized yet - a consequence of a circular reference");
                }
                else {
                    logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
                }
            }
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }

        else {
//2、缓存中获取不到,开始Bean的创建对象流程;
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            // Check if bean definition exists in this factory.
            BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // Not found -> check parent.
                String nameToLookup = originalBeanName(name);
                if (args != null) {
                    // Delegation to parent with explicit args.
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
            }

            if (!typeCheckOnly) {
//3.1标记当前bean已经被创建
                markBeanAsCreated(beanName);
            }

            try {
//3.2获取Bean的定义信息;
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);

//3.3获取当前Bean依赖的其他Bean;如果有,按照getBean()把依赖的Bean先创建出来
                String[] dependsOn = mbd.getDependsOn();
                if (dependsOn != null) {
                    for (String dependsOnBean : dependsOn) {
                        if (isDependent(beanName, dependsOnBean)) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
                        }
                        registerDependentBean(dependsOnBean, beanName);
                        getBean(dependsOnBean);
                    }
                }

//3.4启动单实例Bean的创建流程
                if (mbd.isSingleton()) {
                    sharedInstance = getSingleton(beanName, new ObjectFactory() {
                        @Override
                        public Object getObject() throws BeansException {
                            try {
                                return createBean(beanName, mbd, args);
                            }
                            catch (BeansException ex) {
                                // Explicitly remove instance from singleton cache: It might have been put there
                                // eagerly by the creation process, to allow for circular reference resolution.
                                // Also remove any beans that received a temporary reference to the bean.
                                destroySingleton(beanName);
                                throw ex;
                            }
                        }
                    });
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }

                else if (mbd.isPrototype()) {
                    // It's a prototype -> create a new instance.
                    Object prototypeInstance = null;
                    try {
                        beforePrototypeCreation(beanName);
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                        afterPrototypeCreation(beanName);
                    }
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }

                else {
                    String scopeName = mbd.getScope();
                    final Scope scope = this.scopes.get(scopeName);
                    if (scope == null) {
                        throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                    }
                    try {
                        Object scopedInstance = scope.get(beanName, new ObjectFactory() {
                            @Override
                            public Object getObject() throws BeansException {
                                beforePrototypeCreation(beanName);
                                try {
                                    return createBean(beanName, mbd, args);
                                }
                                finally {
                                    afterPrototypeCreation(beanName);
                                }
                            }
                        });
                        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }
                    catch (IllegalStateException ex) {
                        throw new BeanCreationException(beanName,
                                "Scope '" + scopeName + "' is not active for the current thread; consider " +
                                "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                                ex);
                    }
                }
            }
            catch (BeansException ex) {
                cleanupAfterBeanCreationFailure(beanName);
                throw ex;
            }
        }

        // Check if required type matches the type of the actual bean instance.
        if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
            try {
                return getTypeConverter().convertIfNecessary(bean, requiredType);
            }
            catch (TypeMismatchException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Failed to convert bean '" + name + "' to required type [" +
                            ClassUtils.getQualifiedName(requiredType) + "]", ex);
                }
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
        }
        return (T) bean;
    }

 
 
  • AbstractAutowireCapableBeanFactory.createBean创建有依赖的bean并放入缓存中

12、finishRefresh完成BeanFactory的初始化创建工作

    protected void finishRefresh() {
        //1、初始化和生命周期有关的后置处理器;LifecycleProcessor
        initLifecycleProcessor();

        // 2、拿到前面定义的生命周期处理器(BeanFactory);回调onRefresh();
        getLifecycleProcessor().onRefresh();

        // 3、发布容器刷新完成事件
        publishEvent(new ContextRefreshedEvent(this));

        // 4、Participate in LiveBeansView MBean, if active.
        LiveBeansView.registerApplicationContext(this);
    }

你可能感兴趣的:(6、spring容器创建过程(注解))