springboot启动源码解析

/*
SpringApplication
*/

创新互联公司是专业的烈山网站建设公司,烈山接单;提供网站设计、网站建设,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行烈山网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

//构造器初始化
public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
this.sources = new LinkedHashSet();
//横幅模式 OFF,CONSOLE,LOG;
this.bannerMode = Mode.CONSOLE;
this.logStartupInfo = true;
this.addCommandLineProperties = true;
this.addConversionService = true;
this.headless = true;
this.registerShutdownHook = true;
this.additionalProfiles = new HashSet();
this.isCustomEnvironment = false;
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
//应用类型NONE,SERVLET,REACTIVE;存在DispatcherHandler,不存在DispatcherServlet,ServletContainer,则为REACTIVE
//不存在javax.servlet.Servlet", "org.springframework.web.context.ConfigurableWebApplicationContext,则为NONE,则为SERVLET
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//spring.factories文件中org.springframework.context.ApplicationContextInitializer=\
//org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
//org.springframework.boot.context.ContextIdApplicationContextInitializer,\
//org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
//org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
//org.springframework.context.ApplicationListener=\
//org.springframework.boot.ClearCachesApplicationListener,\
//org.springframework.boot.builder.ParentContextCloserApplicationListener,\
//org.springframework.boot.context.FileEncodingApplicationListener,\
//org.springframework.boot.context.config.AnsiOutputApplicationListener,\
//org.springframework.boot.context.config.ConfigFileApplicationListener,\
//org.springframework.boot.context.config.DelegatingApplicationListener,\
//org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
//org.springframework.boot.context.logging.LoggingApplicationListener,\
//org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener 进行初始化
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
//推论出主类main
this.mainApplicationClass = this.deduceMainApplicationClass();
}
//核心开始运行
public ConfigurableApplicationContext run(String... args) {
//秒表,用于记录启动时间,记录每个任务 的时间,
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//spring应用上下文,spring容器
ConfigurableApplicationContext context = null;
//自定义SpringApplication启动错误的回调接口
Collection exceptionReporters = new ArrayList();
//java.awt.headless模式 默认为true开启
this.configureHeadlessProperty();
//开启监听
//org.springframework.boot.SpringApplicationRunListener=\
//org.springframework.boot.context.event.EventPublishingRunListener
SpringApplicationRunListeners listeners = this.getRunListeners(args);
//
listeners.starting();

    Collection exceptionReporters;
    try {
        //参数封装,在命令行下启动应用带的参数,如--server.port
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        //环境准备 1.加载外部化配置的资源到environment 2.触发ApplicationEnvironmentPreparedEvent事件
        ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
        //配置系统属性spring.beaninfo.ignore
        this.configureIgnoreBeanInfo(environment);
        //打印横幅
        Banner printedBanner = this.printBanner(environment);
        //创建ApplicationContext 根据webApplicationType
        //SERVLET:
        //        contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");
        //REACTIVE:
        //        contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");
        //    default:
        //        contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
        /**
        *AnnotationConfigServletWebServerApplicationContext层级关系-》ServletWebServerApplicationContext-》GenericWebApplicationContext
        *-》GenericApplicationContext-》AbstractApplicationContext
        */
        //部分属性:reader、scanner、beanFactory进行了实例化
        context = this.createApplicationContext();
        //实例化 用来支持报告关于启动的错误
        //# Error Reporters
        //org.springframework.boot.SpringBootExceptionReporter=\
        //org.springframework.boot.diagnostics.FailureAnalyzers
        exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
        //ApplicationContext准备 加载
        this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
        //核心:
        this.refreshContext(context);
        this.afterRefresh(context, applicationArguments);
        stopWatch.stop();
        if (this.logStartupInfo) {
            (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
        }

        listeners.started(context);
        this.callRunners(context, applicationArguments);
    } catch (Throwable var10) {
        this.handleRunFailure(context, var10, exceptionReporters, listeners);
        throw new IllegalStateException(var10);
    }

    try {
        listeners.running(context);
        return context;
    } catch (Throwable var9) {
        this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
        throw new IllegalStateException(var9);
    }
}

//环境准备
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) {
//创建环境 SERVLET StandardServletEnvironment; REACTIVE StandardReactiveWebEnvironment; StandardEnvironment
ConfigurableEnvironment environment = this.getOrCreateEnvironment();
this.configureEnvironment((ConfigurableEnvironment)environment, applicationArguments.getSourceArgs());
listeners.environmentPrepared((ConfigurableEnvironment)environment);
this.bindToSpringApplication((ConfigurableEnvironment)environment);
if (!this.isCustomEnvironment) {
environment = (new EnvironmentConverter(this.getClassLoader())).convertEnvironmentIfNecessary((ConfigurableEnvironment)environment, this.deduceEnvironmentClass());
}

    ConfigurationPropertySources.attach((Environment)environment);
    return (ConfigurableEnvironment)environment;
}

//ApplicationContext准备 加载
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
//设置上下文的environment
context.setEnvironment(environment);
//应用上下文后处理
this.postProcessApplicationContext(context);
//在context refresh之前,对其应用ApplicationContextInitializer
this.applyInitializers(context);
//上下文准备(目前是空实现,有待扩展)
listeners.contextPrepared(context);
//打印启动日志和启动应用profile
if (this.logStartupInfo) {
this.logStartupInfo(context.getParent() == null);
this.logStartupProfileInfo(context);
}
//向beanFactory注册单例bean:命令行参数bean
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
//向beanFactory注册单例bean:banner bean
beanFactory.registerSingleton("springBootBanner", printedBanner);
}

    if (beanFactory instanceof DefaultListableBeanFactory) {
        ((DefaultListableBeanFactory)beanFactory).setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
    }

    Set sources = this.getAllSources();
    Assert.notEmpty(sources, "Sources must not be empty");
    //把bean加载到应用上下文中
    this.load(context, sources.toArray(new Object[0]));
    //向上下文中添加applicationListener,并广播ApplicationPerpareEvent事件
    listeners.contextLoaded(context);
}   

/*
AbstractApplicationContext
*/
//刷新
public void refresh() throws BeansException, IllegalStateException {
Object var1 = this.startupShutdownMonitor;
synchronized(this.startupShutdownMonitor) {
//1.刷新前准备 校验
this.prepareRefresh();
//2.获取DefaultListableBeanFactory实例
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
//3.beanFactory加载配置
this.prepareBeanFactory(beanFactory);

        try {
            //4.BeanFactory准备工作完成后进行的后置准备工作
              //beanFactory后置处理,重写ApplicationContext的postProcessBeanFactory方法 未做处理
            this.postProcessBeanFactory(beanFactory);
            /********以上是BeanFactory的创建及预准备工作********/

            //核心:执行BeanFactoryPostProcessor的方法:
            //BeanFactoryPostProcessor:BeanFactory的后置处理器,在BeanFactory标准初始化之后执行的;
            //他的重要两个接口:BeanFactoryPostProcessor、BeanDefitionRegistryPostProcessor
            this.invokeBeanFactoryPostProcessors(beanFactory);
            //注册BeanPostProcessor(Bean的后置处理器)
            this.registerBeanPostProcessors(beanFactory);
            //7 初始化MessageSource组件(做国际化功能:消息绑定,消息解析)
            this.initMessageSource();
            //8初始化事件派发器
            this.initApplicationEventMulticaster();
            //9子类重写这个方法,在容器刷新的时候可以自定义逻辑
            this.onRefresh();
            //10.给容器中所有项目里面的ApplicationListener注册进来
            this.registerListeners();
            //11.初始化所有剩下的单实例bean
            this.finishBeanFactoryInitialization(beanFactory);
            //12.完成beanFactory的初始化创建工作:IOC容器就创建完成
            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();
        }

    }
}  
/**

AbstractApplicationContext
/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
//1 设置BeanFactory的类加载器
beanFactory.setBeanClassLoader(this.getClassLoader());
//2 设置支持表达式解析器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, this.getEnvironment()));
//3 添加部分BeanPostProcessor
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//4 设置忽略的自动装配的接口EnvironmentAware、EmbeddedValueResolverAware、xxx;
//这些接口的实现类不能通过类型来自动注入
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
//5 注册可以解析的自动装配:我们能直接在任何组件中自动注入://BeanFactory/ResourceLoader、ApplicationEventPublisher、ApplicationContext
//使用:
//@Autowired
br/>//BeanFactory/ResourceLoader、ApplicationEventPublisher、ApplicationContext
//使用:
//@Autowired
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
//6 添加BeanPostProcessor后置处理器
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
//7 添加编译时AspectJ
if (beanFactory.containsBean("loadTimeWeaver")) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
//8 注册组件
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());
    }

}

/*
AbstractApplicationContext
*/
//执行BeanFactoryPostProcessor的后置处理器方法
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()));
}

}

/*
PostProcessorRegistrationDelegate

*/
public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors) {
Set processedBeans = new HashSet();
ArrayList regularPostProcessors;
ArrayList registryProcessors;
int var9;
ArrayList currentRegistryProcessors;
String[] postProcessorNames;
//1.判断beanFactory是否为BeanDefinitionRegistry,beanFactory为DefaultListableBeanFactory,
//而DefaultListableBeanFactory实现了BeanDefinitionRegistry接口
if (beanFactory instanceof BeanDefinitionRegistry) {
//强转成BeanDefinitionRegistry
BeanDefinitionRegistry registry = (BeanDefinitionRegistry)beanFactory;
//保存BeanFactoryPostProcessor类型的后置处理器
regularPostProcessors = new ArrayList();
//保存BeanDefinitionRegistryPostProcessor类型的后置处理器
registryProcessors = new ArrayList();
Iterator var6 = beanFactoryPostProcessors.iterator();
//循环遍历beanFactoryPostProcessors
while(var6.hasNext()) {
BeanFactoryPostProcessor postProcessor = (BeanFactoryPostProcessor)var6.next();
//判断是否BeanDefinitionRegistryPostProcessor
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
//强转BeanDefinitionRegistryPostProcessor
BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor)postProcessor;
//调用后置方法
registryProcessor.postProcessBeanDefinitionRegistry(registry);
//添加到集合当中
registryProcessors.add(registryProcessor);
} else {
//没有实现BeanDefinitionRegistryPostProcessor接口,添加到regularPostProcessors集合中
regularPostProcessors.add(postProcessor);
}
}
//定义一个集合保存当前准备创建的BeanDefinitionRegistryPostProcessor
currentRegistryProcessors = new ArrayList();
//第一步:去容器中获取BeanDefinitionRegistryPostProcessor的bean的处理器名称
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
String[] var16 = postProcessorNames;
var9 = postProcessorNames.length;

        int var10;
        String ppName;
        //循环遍历获取BeanDefinitionRegistryPostProcessor的类型名称
        for(var10 = 0; var10 < var9; ++var10) {
            ppName = var16[var10];
            //判断是否实现了PriorityOrdered接口
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                //调用getBean方法获取该对象加入currentRegistryProcessors集合中
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                //同时加入processedBeans集合中
                processedBeans.add(ppName);
            }
        }
        //对currentRegistryProcessors集合中BeanDefinitionRegistryPostProcessor进行排序
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        //保存到registryProcessors中
        registryProcessors.addAll(currentRegistryProcessors);
        /**
        *核心:典型的BeanDefinitionRegistryPostProcessor是ConfigurationClassPostProcessor
        *用于进行bean定义的加载  ->processConfigBeanDefinitions方法
        */
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        //1清除当前临时集合currentRegistryProcessors
        currentRegistryProcessors.clear();
        //又在容器中获取BeanDefinitionRegistryPostProcessor的bean处理器名称
        postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        var16 = postProcessorNames;
        var9 = postProcessorNames.length;

        for(var10 = 0; var10 < var9; ++var10) {
            ppName = var16[var10];
            //没被处理过 且实现了Ordered接口
            if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                //调用getBean方法获取该对象加入currentRegistryProcessors集合中
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                //同时加入processedBeans集合中
                processedBeans.add(ppName);
            }
        }
        //对currentRegistryProcessors集合中BeanDefinitionRegistryPostProcessor进行排序
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        //保存到registryProcessors中
        registryProcessors.addAll(currentRegistryProcessors);
        //调用后置处理方法
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        //2清除当前临时集合currentRegistryProcessors
        currentRegistryProcessors.clear();
        boolean reiterate = true;
        //调用没有实现任何优先级接口的BeanDefinitionRegistryPostProcessor
        while(reiterate) {
            //进入循环把reiterate更新为false
            reiterate = false;
            //在容器中获取BeanDefinitionRegistryPostProcessor的bean处理器名称
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            String[] var19 = postProcessorNames;
            var10 = postProcessorNames.length;

            for(int var26 = 0; var26 < var10; ++var26) {
                String ppName = var19[var26];
                //没有被处理过的
                if (!processedBeans.contains(ppName)) {
                    //调用getBean方法获取该对象加入currentRegistryProcessors集合中
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    //同时加入processedBeans集合中
                    processedBeans.add(ppName);

                    reiterate = true;
                }
            }
            ////对currentRegistryProcessors集合中BeanDefinitionRegistryPostProcessor进行排序
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            //保存到registryProcessors中
            registryProcessors.addAll(currentRegistryProcessors);
            //调用后置处理方法
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            //3清除当前临时集合currentRegistryProcessors
            currentRegistryProcessors.clear();
        }
        //调用实现了BeanDefinitionRegistryPostProcessor接口和BeanFactoryPostProcessor接口的方法
        invokeBeanFactoryPostProcessors((Collection)registryProcessors, (ConfigurableListableBeanFactory)beanFactory);
        //调用实现了BeanFactoryPostProcessor接口的方法
        invokeBeanFactoryPostProcessors((Collection)regularPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
    } else {
        //beanFactory没有实现了BeanDefinitionRegistry 直接调用beanFactoryPostProcessor接口的方法进行后置处理器
        invokeBeanFactoryPostProcessors((Collection)beanFactoryPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
    }
    //最后 获取容器中所有的BeanFactoryPostProcessor
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
    //保存实现了priorityOrdered接口
    regularPostProcessors = new ArrayList();
    //保存实现了Ordered接口
    registryProcessors = new ArrayList();
    currentRegistryProcessors = new ArrayList();
    postProcessorNames = postProcessorNames;//错误代码
    int var20 = postProcessorNames.length;

    String ppName;
    for(var9 = 0; var9 < var20; ++var9) {
        ppName = postProcessorNames[var9];
        //没被处理过
        if (!processedBeans.contains(ppName)) {
            //判断是否实现了PriorityOrdered
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                regularPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
            //判断是否实现了Ordered
            } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
                registryProcessors.add(ppName);
            } else {
                //没有任何优先级接口
                currentRegistryProcessors.add(ppName);
            }
        }
    }

    sortPostProcessors(regularPostProcessors, beanFactory);
    //先调用BeanFactoryPostProcessor实现了priorityOrdered接口
    invokeBeanFactoryPostProcessors((Collection)regularPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
    List orderedPostProcessors = new ArrayList();
    Iterator var21 = registryProcessors.iterator();

    while(var21.hasNext()) {
        String postProcessorName = (String)var21.next();
        orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    //再调用BeanFactoryPostProcessor实现了Ordered接口
    sortPostProcessors(orderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors((Collection)orderedPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
    List nonOrderedPostProcessors = new ArrayList();
    Iterator var24 = currentRegistryProcessors.iterator();

    while(var24.hasNext()) {
        ppName = (String)var24.next();
        nonOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
    }
    //最后调用没有实现任何方法接口
    invokeBeanFactoryPostProcessors((Collection)nonOrderedPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
    beanFactory.clearMetadataCache();
}

/*
ConfigurationClassPostProcessor

/
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
//
List configCandidates = new ArrayList();
//获取springIOC容器中目前所有bean定义的名称
String[] candidateNames = registry.getBeanDefinitionNames();
String[] var4 = candidateNames;
int var5 = candidateNames.length;
//循环所有的Bean定义信息
for(int var6 = 0; var6 < var5; ++var6) {
String beanName = var4[var6];
//通过bean的名称来获取bean的定义对象
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
//判断是否解析过
if (!ConfigurationClassUtils.isFullConfigurationClass(beanDef) && !ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
//判读是否是配置类
if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
//添加到候选的配置类集合中
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
} else if (this.logger.isDebugEnabled()) {
this.logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}

    if (!configCandidates.isEmpty()) {
        //对配置类进行Order排序
        configCandidates.sort((bd1, bd2) -> {
            int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
            int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
            return Integer.compare(i1, i2);
        });
        //创建@CompentScan、@Import导入进来的bean名称的生成器
        SingletonBeanRegistry sbr = null;
        if (registry instanceof SingletonBeanRegistry) {
            sbr = (SingletonBeanRegistry)registry;
            if (!this.localBeanNameGeneratorSet) {
                BeanNameGenerator generator = (BeanNameGenerator)sbr.getSingleton("org.springframework.context.annotation.internalConfigurationBeanNameGenerator");
                if (generator != null) {
                    //设置@CompentScan导入进来的bean的名称生成器
                    this.componentScanBeanNameGenerator = generator;
                    //设置@Import导入进来的bean的名称生成器
                    this.importBeanNameGenerator = generator;
                }
            }
        }

        if (this.environment == null) {
            this.environment = new StandardEnvironment();
        }
        //创建配置类解析器对象
        ConfigurationClassParser parser = new ConfigurationClassParser(this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, this.componentScanBeanNameGenerator, registry);
        //创建集合用于保存我们的配置类BeanDefinitionHolder集合默认长度是配置类集合的长度
        Set candidates = new LinkedHashSet(configCandidates);
        //创建集合用于保存已经解析的配置类,长度默认解析出来配置类的集合长度
        HashSet alreadyParsed = new HashSet(configCandidates.size());

        do {
            //真正解析配置类
            /**
            *核心解析:ConfigurationClassParser->parse
            */
            parser.parse(candidates);
            parser.validate();
            //解析出来的配置类
            Set configClasses = new LinkedHashSet(parser.getConfigurationClasses());
            configClasses.removeAll(alreadyParsed);
            if (this.reader == null) {
                this.reader = new ConfigurationClassBeanDefinitionReader(registry, this.sourceExtractor, this.resourceLoader, this.environment, this.importBeanNameGenerator, parser.getImportRegistry());
            }
            //把解析出的配置类注册到容器中
            this.reader.loadBeanDefinitions(configClasses);
            //加入已经解析出的集合
            alreadyParsed.addAll(configClasses);
            candidates.clear();
            //判断我们springIOC容器中Bean的定义数量是否大于候选原始的bean定义的个数
            if (registry.getBeanDefinitionCount() > candidateNames.length) {
                //获取所有bean的定义
                String[] newCandidateNames = registry.getBeanDefinitionNames();
                //原始的老的候选的bean定义
                Set oldCandidateNames = new HashSet(Arrays.asList(candidateNames));
                Set alreadyParsedClasses = new HashSet();
                Iterator var12 = alreadyParsed.iterator();

                while(var12.hasNext()) {
                    //添加已解析的
                    ConfigurationClass configurationClass = (ConfigurationClass)var12.next();
                    alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
                }

                String[] var23 = newCandidateNames;
                int var24 = newCandidateNames.length;

                for(int var14 = 0; var14 < var24; ++var14) {
                    String candidateName = var23[var14];
                    //当前还没有被解析过
                    if (!oldCandidateNames.contains(candidateName)) {
                        BeanDefinition bd = registry.getBeanDefinition(candidateName);
                        //判断有没有被解析过
                        if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) && !alreadyParsedClasses.contains(bd.getBeanClassName())) {
                            candidates.add(new BeanDefinitionHolder(bd, candidateName));
                        }
                    }
                }

                candidateNames = newCandidateNames;
            }
            //存在没有解析过的,需循环解析
        } while(!candidates.isEmpty());

        if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
            sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
        }

        if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
            ((CachingMetadataReaderFactory)this.metadataReaderFactory).clearCache();
        }

    }
}

/*
ConfigurationClassParser
*/
public void parse(Set configCandidates) {
Iterator var2 = configCandidates.iterator();

    while(var2.hasNext()) {
        BeanDefinitionHolder holder = (BeanDefinitionHolder)var2.next();
        BeanDefinition bd = holder.getBeanDefinition();

        try {
            //真正的解析bean定义
            if (bd instanceof AnnotatedBeanDefinition) {
                this.parse(((AnnotatedBeanDefinition)bd).getMetadata(), holder.getBeanName());
            } else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition)bd).hasBeanClass()) {
                this.parse(((AbstractBeanDefinition)bd).getBeanClass(), holder.getBeanName());
            } else {
                this.parse(bd.getBeanClassName(), holder.getBeanName());
            }
        } catch (BeanDefinitionStoreException var6) {
            throw var6;
        } catch (Throwable var7) {
            throw new BeanDefinitionStoreException("Failed to parse configuration class [" + bd.getBeanClassName() + "]", var7);
        }
    }
    //处理延时的DeferredImportSelectors spring boot 是通过这步进行spring.factories文件中的自定装配的对象
    this.deferredImportSelectorHandler.process();
}

protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
//把我们配置类源信息和beanName包装成一个ConfigurationClass对象
this.processConfigurationClass(new ConfigurationClass(metadata, beanName));
}

protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
if (!this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
//获取配置类对象
ConfigurationClass existingClass = (ConfigurationClass)this.configurationClasses.get(configClass);
if (existingClass != null) {
//传入的配置类是通过其他配置类的Import导入进来
if (configClass.isImported()) {
if (existingClass.isImported()) {
//合并配置
existingClass.mergeImportedBy(configClass);
}

                return;
            }

            this.configurationClasses.remove(configClass);
            this.knownSuperclasses.values().removeIf(configClass::equals);
        }

        ConfigurationClassParser.SourceClass sourceClass = this.asSourceClass(configClass);

        do {
            //解析配置类
            sourceClass = this.doProcessConfigurationClass(configClass, sourceClass);
        } while(sourceClass != null);

        this.configurationClasses.put(configClass, configClass);
    }
}

@Nullable
protected final ConfigurationClassParser.SourceClass doProcessConfigurationClass(ConfigurationClass configClass, ConfigurationClassParser.SourceClass sourceClass) throws IOException {
if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
this.processMemberClasses(configClass, sourceClass);}
//处理@PropertySources注解的
br/>}
//处理@PropertySources注解的

    AnnotationAttributes importResource;
    while(var3.hasNext()) {
        importResource = (AnnotationAttributes)var3.next();
        if (this.environment instanceof ConfigurableEnvironment) {
            this.processPropertySource(importResource);
        } else {
            this.logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() + "]. Reason: Environment must implement ConfigurableEnvironment");
        }
    }
    //处理@ComponentScans注解的
    Set componentScans = AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
    if (!componentScans.isEmpty() && !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
        Iterator var13 = componentScans.iterator();

        while(var13.hasNext()) {
            AnnotationAttributes componentScan = (AnnotationAttributes)var13.next();
            /**
            *ComponentScanAnnotationParser->parse
            */
            Set scannedBeanDefinitions = this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
            Iterator var7 = scannedBeanDefinitions.iterator();

            while(var7.hasNext()) {
                BeanDefinitionHolder holder = (BeanDefinitionHolder)var7.next();
                BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
                if (bdCand == null) {
                    bdCand = holder.getBeanDefinition();
                }
                //判断当前扫描出来的bean定义是不是配置类,是,进行递归解析
                if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
                    //递归解析
                    this.parse(bdCand.getBeanClassName(), holder.getBeanName());
                }
            }
        }
    }
    //处理@Import
    this.processImports(configClass, sourceClass, this.getImports(sourceClass), true);
    //处理@ImportResource
    importResource = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
    if (importResource != null) {
        String[] resources = importResource.getStringArray("locations");
        Class readerClass = importResource.getClass("reader");
        String[] var19 = resources;
        int var21 = resources.length;

        for(int var22 = 0; var22 < var21; ++var22) {
            String resource = var19[var22];
            String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
            configClass.addImportedResource(resolvedResource, readerClass);
        }
    }
    //处理@Bean methods获取到我们配置类中所有标注了@Bean的方法
    Set beanMethods = this.retrieveBeanMethodMetadata(sourceClass);
    Iterator var17 = beanMethods.iterator();

    while(var17.hasNext()) {
        MethodMetadata methodMetadata = (MethodMetadata)var17.next();
        configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
    }
    //处理配置类接口
    this.processInterfaces(configClass, sourceClass);
    //处理配置类的父类
    if (sourceClass.getMetadata().hasSuperClass()) {
        String superclass = sourceClass.getMetadata().getSuperClassName();
        if (superclass != null && !superclass.startsWith("java") && !this.knownSuperclasses.containsKey(superclass)) {
            this.knownSuperclasses.put(superclass, configClass);
            return sourceClass.getSuperClass();
        }
    }

    return null;
}

/*
ComponentScanAnnotationParser
*/
public Set parse(AnnotationAttributes componentScan, final String declaringClass) {
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry, componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
//给扫描器设置beanName的生成器对象
Class generatorClass = componentScan.getClass("nameGenerator");
boolean useInheritedGenerator = BeanNameGenerator.class == generatorClass;
scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator : (BeanNameGenerator)BeanUtils.instantiateClass(generatorClass));
//设置bean的域代理模型
ScopedProxyMode scopedProxyMode = (ScopedProxyMode)componentScan.getEnum("scopedProxy");
if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
scanner.setScopedProxyMode(scopedProxyMode);
} else {
Class resolverClass = componentScan.getClass("scopeResolver");
scanner.setScopeMetadataResolver((ScopeMetadataResolver)BeanUtils.instantiateClass(resolverClass));
}

    scanner.setResourcePattern(componentScan.getString("resourcePattern"));
    //设置ComponentScan对象的includeFilters包含的属性
    AnnotationAttributes[] var15 = componentScan.getAnnotationArray("includeFilters");
    int var8 = var15.length;

    int var9;
    AnnotationAttributes filter;
    Iterator var11;
    TypeFilter typeFilter;
    for(var9 = 0; var9 < var8; ++var9) {
        filter = var15[var9];
        var11 = this.typeFiltersFor(filter).iterator();

        while(var11.hasNext()) {
            typeFilter = (TypeFilter)var11.next();
            scanner.addIncludeFilter(typeFilter);
        }
    }
    //设置ComponentScan对象的excludeFilters不包含的属性
    var15 = componentScan.getAnnotationArray("excludeFilters");
    var8 = var15.length;

    for(var9 = 0; var9 < var8; ++var9) {
        filter = var15[var9];
        var11 = this.typeFiltersFor(filter).iterator();

        while(var11.hasNext()) {
            typeFilter = (TypeFilter)var11.next();
            scanner.addExcludeFilter(typeFilter);
        }
    }
    //是否懒加载
    boolean lazyInit = componentScan.getBoolean("lazyInit");
    if (lazyInit) {
        scanner.getBeanDefinitionDefaults().setLazyInit(true);
    }
    //包路径
    Set basePackages = new LinkedHashSet();
    String[] basePackagesArray = componentScan.getStringArray("basePackages");
    String[] var19 = basePackagesArray;
    int var21 = basePackagesArray.length;

    int var22;
    for(var22 = 0; var22 < var21; ++var22) {
        String pkg = var19[var22];
        String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg), ",; \t\n");
        Collections.addAll(basePackages, tokenized);
    }

    Class[] var20 = componentScan.getClassArray("basePackageClasses");
    var21 = var20.length;

    for(var22 = 0; var22 < var21; ++var22) {
        Class clazz = var20[var22];
        basePackages.add(ClassUtils.getPackageName(clazz));
    }

    if (basePackages.isEmpty()) {
        basePackages.add(ClassUtils.getPackageName(declaringClass));
    }

    scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
        protected boolean matchClassName(String className) {
            return declaringClass.equals(className);
        }
    });
    //真正的进行扫描解析
    return scanner.doScan(StringUtils.toStringArray(basePackages));
}

分享文章:springboot启动源码解析
地址分享:http://bzwzjz.com/article/pogpps.html