溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

springboot啟動(dòng)源碼解析

發(fā)布時(shí)間:2020-07-09 11:38:33 來源:網(wǎng)絡(luò) 閱讀:347 作者:mufeng07 欄目:編程語言

/*
SpringApplication
*/

//構(gòu)造器初始化
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));
//應(yīng)用類型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 進(jìn)行初始化
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
//推論出主類main
this.mainApplicationClass = this.deduceMainApplicationClass();
}
//核心開始運(yùn)行
public ConfigurableApplicationContext run(String... args) {
//秒表,用于記錄啟動(dòng)時(shí)間,記錄每個(gè)任務(wù) 的時(shí)間,
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//spring應(yīng)用上下文,spring容器
ConfigurableApplicationContext context = null;
//自定義SpringApplication啟動(dòng)錯(cuò)誤的回調(diào)接口
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
//java.awt.headless模式 默認(rèn)為true開啟
this.configureHeadlessProperty();
//開啟監(jiān)聽
//org.springframework.boot.SpringApplicationRunListener=\
//org.springframework.boot.context.event.EventPublishingRunListener
SpringApplicationRunListeners listeners = this.getRunListeners(args);
//
listeners.starting();

    Collection exceptionReporters;
    try {
        //參數(shù)封裝,在命令行下啟動(dòng)應(yīng)用帶的參數(shù),如--server.port
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        //環(huán)境準(zhǔn)備 1.加載外部化配置的資源到environment 2.觸發(fā)ApplicationEnvironmentPreparedEvent事件
        ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
        //配置系統(tǒng)屬性spring.beaninfo.ignore
        this.configureIgnoreBeanInfo(environment);
        //打印橫幅
        Banner printedBanner = this.printBanner(environment);
        //創(chuàng)建ApplicationContext 根據(jù)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層級(jí)關(guān)系-》ServletWebServerApplicationContext-》GenericWebApplicationContext
        *-》GenericApplicationContext-》AbstractApplicationContext
        */
        //部分屬性:reader、scanner、beanFactory進(jìn)行了實(shí)例化
        context = this.createApplicationContext();
        //實(shí)例化 用來支持報(bào)告關(guān)于啟動(dòng)的錯(cuò)誤
        //# Error Reporters
        //org.springframework.boot.SpringBootExceptionReporter=\
        //org.springframework.boot.diagnostics.FailureAnalyzers
        exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
        //ApplicationContext準(zhǔn)備 加載
        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);
    }
}

//環(huán)境準(zhǔn)備
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) {
//創(chuàng)建環(huán)境 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準(zhǔn)備 加載
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
//設(shè)置上下文的environment
context.setEnvironment(environment);
//應(yīng)用上下文后處理
this.postProcessApplicationContext(context);
//在context refresh之前,對(duì)其應(yīng)用ApplicationContextInitializer
this.applyInitializers(context);
//上下文準(zhǔn)備(目前是空實(shí)現(xiàn),有待擴(kuò)展)
listeners.contextPrepared(context);
//打印啟動(dòng)日志和啟動(dòng)應(yīng)用profile
if (this.logStartupInfo) {
this.logStartupInfo(context.getParent() == null);
this.logStartupProfileInfo(context);
}
//向beanFactory注冊(cè)單例bean:命令行參數(shù)bean
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
//向beanFactory注冊(cè)單例bean:banner bean
beanFactory.registerSingleton("springBootBanner", printedBanner);
}

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

    Set<Object> sources = this.getAllSources();
    Assert.notEmpty(sources, "Sources must not be empty");
    //把bean加載到應(yīng)用上下文中
    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.刷新前準(zhǔn)備 校驗(yàn)
this.prepareRefresh();
//2.獲取DefaultListableBeanFactory實(shí)例
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
//3.beanFactory加載配置
this.prepareBeanFactory(beanFactory);

        try {
            //4.BeanFactory準(zhǔn)備工作完成后進(jìn)行的后置準(zhǔn)備工作
              //beanFactory后置處理,重寫ApplicationContext的postProcessBeanFactory方法 未做處理
            this.postProcessBeanFactory(beanFactory);
            /********以上是BeanFactory的創(chuàng)建及預(yù)準(zhǔn)備工作********/

            //核心:執(zhí)行BeanFactoryPostProcessor的方法:
            //BeanFactoryPostProcessor:BeanFactory的后置處理器,在BeanFactory標(biāo)準(zhǔn)初始化之后執(zhí)行的;
            //他的重要兩個(gè)接口:BeanFactoryPostProcessor、BeanDefitionRegistryPostProcessor
            this.invokeBeanFactoryPostProcessors(beanFactory);
            //注冊(cè)BeanPostProcessor(Bean的后置處理器)
            this.registerBeanPostProcessors(beanFactory);
            //7 初始化MessageSource組件(做國際化功能:消息綁定,消息解析)
            this.initMessageSource();
            //8初始化事件派發(fā)器
            this.initApplicationEventMulticaster();
            //9子類重寫這個(gè)方法,在容器刷新的時(shí)候可以自定義邏輯
            this.onRefresh();
            //10.給容器中所有項(xiàng)目里面的ApplicationListener注冊(cè)進(jìn)來
            this.registerListeners();
            //11.初始化所有剩下的單實(shí)例bean
            this.finishBeanFactoryInitialization(beanFactory);
            //12.完成beanFactory的初始化創(chuàng)建工作:IOC容器就創(chuàng)建完成
            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 設(shè)置BeanFactory的類加載器
beanFactory.setBeanClassLoader(this.getClassLoader());
//2 設(shè)置支持表達(dá)式解析器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, this.getEnvironment()));
//3 添加部分BeanPostProcessor
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//4 設(shè)置忽略的自動(dòng)裝配的接口EnvironmentAware、EmbeddedValueResolverAware、xxx;
//這些接口的實(shí)現(xiàn)類不能通過類型來自動(dòng)注入
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 注冊(cè)可以解析的自動(dòng)裝配:我們能直接在任何組件中自動(dòng)注入://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 添加編譯時(shí)AspectJ
if (beanFactory.containsBean("loadTimeWeaver")) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
//8 注冊(cè)組件
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
*/
//執(zhí)行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<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
Set<String> processedBeans = new HashSet();
ArrayList regularPostProcessors;
ArrayList registryProcessors;
int var9;
ArrayList currentRegistryProcessors;
String[] postProcessorNames;
//1.判斷beanFactory是否為BeanDefinitionRegistry,beanFactory為DefaultListableBeanFactory,
//而DefaultListableBeanFactory實(shí)現(xiàn)了BeanDefinitionRegistry接口
if (beanFactory instanceof BeanDefinitionRegistry) {
//強(qiáng)轉(zhuǎn)成BeanDefinitionRegistry
BeanDefinitionRegistry registry = (BeanDefinitionRegistry)beanFactory;
//保存BeanFactoryPostProcessor類型的后置處理器
regularPostProcessors = new ArrayList();
//保存BeanDefinitionRegistryPostProcessor類型的后置處理器
registryProcessors = new ArrayList();
Iterator var6 = beanFactoryPostProcessors.iterator();
//循環(huán)遍歷beanFactoryPostProcessors
while(var6.hasNext()) {
BeanFactoryPostProcessor postProcessor = (BeanFactoryPostProcessor)var6.next();
//判斷是否BeanDefinitionRegistryPostProcessor
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
//強(qiáng)轉(zhuǎn)BeanDefinitionRegistryPostProcessor
BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor)postProcessor;
//調(diào)用后置方法
registryProcessor.postProcessBeanDefinitionRegistry(registry);
//添加到集合當(dāng)中
registryProcessors.add(registryProcessor);
} else {
//沒有實(shí)現(xiàn)BeanDefinitionRegistryPostProcessor接口,添加到regularPostProcessors集合中
regularPostProcessors.add(postProcessor);
}
}
//定義一個(gè)集合保存當(dāng)前準(zhǔn)備創(chuàng)建的BeanDefinitionRegistryPostProcessor
currentRegistryProcessors = new ArrayList();
//第一步:去容器中獲取BeanDefinitionRegistryPostProcessor的bean的處理器名稱
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
String[] var16 = postProcessorNames;
var9 = postProcessorNames.length;

        int var10;
        String ppName;
        //循環(huán)遍歷獲取BeanDefinitionRegistryPostProcessor的類型名稱
        for(var10 = 0; var10 < var9; ++var10) {
            ppName = var16[var10];
            //判斷是否實(shí)現(xiàn)了PriorityOrdered接口
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                //調(diào)用getBean方法獲取該對(duì)象加入currentRegistryProcessors集合中
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                //同時(shí)加入processedBeans集合中
                processedBeans.add(ppName);
            }
        }
        //對(duì)currentRegistryProcessors集合中BeanDefinitionRegistryPostProcessor進(jìn)行排序
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        //保存到registryProcessors中
        registryProcessors.addAll(currentRegistryProcessors);
        /**
        *核心:典型的BeanDefinitionRegistryPostProcessor是ConfigurationClassPostProcessor
        *用于進(jìn)行bean定義的加載  ->processConfigBeanDefinitions方法
        */
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        //1清除當(dāng)前臨時(shí)集合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];
            //沒被處理過 且實(shí)現(xiàn)了Ordered接口
            if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                //調(diào)用getBean方法獲取該對(duì)象加入currentRegistryProcessors集合中
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                //同時(shí)加入processedBeans集合中
                processedBeans.add(ppName);
            }
        }
        //對(duì)currentRegistryProcessors集合中BeanDefinitionRegistryPostProcessor進(jìn)行排序
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        //保存到registryProcessors中
        registryProcessors.addAll(currentRegistryProcessors);
        //調(diào)用后置處理方法
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        //2清除當(dāng)前臨時(shí)集合currentRegistryProcessors
        currentRegistryProcessors.clear();
        boolean reiterate = true;
        //調(diào)用沒有實(shí)現(xiàn)任何優(yōu)先級(jí)接口的BeanDefinitionRegistryPostProcessor
        while(reiterate) {
            //進(jìn)入循環(huán)把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)) {
                    //調(diào)用getBean方法獲取該對(duì)象加入currentRegistryProcessors集合中
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    //同時(shí)加入processedBeans集合中
                    processedBeans.add(ppName);

                    reiterate = true;
                }
            }
            ////對(duì)currentRegistryProcessors集合中BeanDefinitionRegistryPostProcessor進(jìn)行排序
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            //保存到registryProcessors中
            registryProcessors.addAll(currentRegistryProcessors);
            //調(diào)用后置處理方法
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            //3清除當(dāng)前臨時(shí)集合currentRegistryProcessors
            currentRegistryProcessors.clear();
        }
        //調(diào)用實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor接口和BeanFactoryPostProcessor接口的方法
        invokeBeanFactoryPostProcessors((Collection)registryProcessors, (ConfigurableListableBeanFactory)beanFactory);
        //調(diào)用實(shí)現(xiàn)了BeanFactoryPostProcessor接口的方法
        invokeBeanFactoryPostProcessors((Collection)regularPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
    } else {
        //beanFactory沒有實(shí)現(xiàn)了BeanDefinitionRegistry 直接調(diào)用beanFactoryPostProcessor接口的方法進(jìn)行后置處理器
        invokeBeanFactoryPostProcessors((Collection)beanFactoryPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
    }
    //最后 獲取容器中所有的BeanFactoryPostProcessor
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
    //保存實(shí)現(xiàn)了priorityOrdered接口
    regularPostProcessors = new ArrayList();
    //保存實(shí)現(xiàn)了Ordered接口
    registryProcessors = new ArrayList();
    currentRegistryProcessors = new ArrayList();
    postProcessorNames = postProcessorNames;//錯(cuò)誤代碼
    int var20 = postProcessorNames.length;

    String ppName;
    for(var9 = 0; var9 < var20; ++var9) {
        ppName = postProcessorNames[var9];
        //沒被處理過
        if (!processedBeans.contains(ppName)) {
            //判斷是否實(shí)現(xiàn)了PriorityOrdered
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                regularPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
            //判斷是否實(shí)現(xiàn)了Ordered
            } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
                registryProcessors.add(ppName);
            } else {
                //沒有任何優(yōu)先級(jí)接口
                currentRegistryProcessors.add(ppName);
            }
        }
    }

    sortPostProcessors(regularPostProcessors, beanFactory);
    //先調(diào)用BeanFactoryPostProcessor實(shí)現(xiàn)了priorityOrdered接口
    invokeBeanFactoryPostProcessors((Collection)regularPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
    List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList();
    Iterator var21 = registryProcessors.iterator();

    while(var21.hasNext()) {
        String postProcessorName = (String)var21.next();
        orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    //再調(diào)用BeanFactoryPostProcessor實(shí)現(xiàn)了Ordered接口
    sortPostProcessors(orderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors((Collection)orderedPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList();
    Iterator var24 = currentRegistryProcessors.iterator();

    while(var24.hasNext()) {
        ppName = (String)var24.next();
        nonOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
    }
    //最后調(diào)用沒有實(shí)現(xiàn)任何方法接口
    invokeBeanFactoryPostProcessors((Collection)nonOrderedPostProcessors, (ConfigurableListableBeanFactory)beanFactory);
    beanFactory.clearMetadataCache();
}

/*
ConfigurationClassPostProcessor

/
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
//
List<BeanDefinitionHolder> configCandidates = new ArrayList();
//獲取springIOC容器中目前所有bean定義的名稱
String[] candidateNames = registry.getBeanDefinitionNames();
String[] var4 = candidateNames;
int var5 = candidateNames.length;
//循環(huán)所有的Bean定義信息
for(int var6 = 0; var6 < var5; ++var6) {
String beanName = var4[var6];
//通過bean的名稱來獲取bean的定義對(duì)象
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()) {
        //對(duì)配置類進(jìn)行Order排序
        configCandidates.sort((bd1, bd2) -> {
            int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
            int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
            return Integer.compare(i1, i2);
        });
        //創(chuàng)建@CompentScan、@Import導(dǎo)入進(jìn)來的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) {
                    //設(shè)置@CompentScan導(dǎo)入進(jìn)來的bean的名稱生成器
                    this.componentScanBeanNameGenerator = generator;
                    //設(shè)置@Import導(dǎo)入進(jìn)來的bean的名稱生成器
                    this.importBeanNameGenerator = generator;
                }
            }
        }

        if (this.environment == null) {
            this.environment = new StandardEnvironment();
        }
        //創(chuàng)建配置類解析器對(duì)象
        ConfigurationClassParser parser = new ConfigurationClassParser(this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, this.componentScanBeanNameGenerator, registry);
        //創(chuàng)建集合用于保存我們的配置類BeanDefinitionHolder集合默認(rèn)長度是配置類集合的長度
        Set<BeanDefinitionHolder> candidates = new LinkedHashSet(configCandidates);
        //創(chuàng)建集合用于保存已經(jīng)解析的配置類,長度默認(rèn)解析出來配置類的集合長度
        HashSet alreadyParsed = new HashSet(configCandidates.size());

        do {
            //真正解析配置類
            /**
            *核心解析:ConfigurationClassParser->parse
            */
            parser.parse(candidates);
            parser.validate();
            //解析出來的配置類
            Set<ConfigurationClass> 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());
            }
            //把解析出的配置類注冊(cè)到容器中
            this.reader.loadBeanDefinitions(configClasses);
            //加入已經(jīng)解析出的集合
            alreadyParsed.addAll(configClasses);
            candidates.clear();
            //判斷我們springIOC容器中Bean的定義數(shù)量是否大于候選原始的bean定義的個(gè)數(shù)
            if (registry.getBeanDefinitionCount() > candidateNames.length) {
                //獲取所有bean的定義
                String[] newCandidateNames = registry.getBeanDefinitionNames();
                //原始的老的候選的bean定義
                Set<String> oldCandidateNames = new HashSet(Arrays.asList(candidateNames));
                Set<String> 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];
                    //當(dāng)前還沒有被解析過
                    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;
            }
            //存在沒有解析過的,需循環(huán)解析
        } 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<BeanDefinitionHolder> 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);
        }
    }
    //處理延時(shí)的DeferredImportSelectors spring boot 是通過這步進(jìn)行spring.factories文件中的自定裝配的對(duì)象
    this.deferredImportSelectorHandler.process();
}

protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
//把我們配置類源信息和beanName包裝成一個(gè)ConfigurationClass對(duì)象
this.processConfigurationClass(new ConfigurationClass(metadata, beanName));
}

protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
if (!this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
//獲取配置類對(duì)象
ConfigurationClass existingClass = (ConfigurationClass)this.configurationClasses.get(configClass);
if (existingClass != null) {
//傳入的配置類是通過其他配置類的Import導(dǎo)入進(jìn)來
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<AnnotationAttributes> 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<BeanDefinitionHolder> 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();
                }
                //判斷當(dāng)前掃描出來的bean定義是不是配置類,是,進(jìn)行遞歸解析
                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<? extends BeanDefinitionReader> 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獲取到我們配置類中所有標(biāo)注了@Bean的方法
    Set<MethodMetadata> 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<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry, componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
//給掃描器設(shè)置beanName的生成器對(duì)象
Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
boolean useInheritedGenerator = BeanNameGenerator.class == generatorClass;
scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator : (BeanNameGenerator)BeanUtils.instantiateClass(generatorClass));
//設(shè)置bean的域代理模型
ScopedProxyMode scopedProxyMode = (ScopedProxyMode)componentScan.getEnum("scopedProxy");
if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
scanner.setScopedProxyMode(scopedProxyMode);
} else {
Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
scanner.setScopeMetadataResolver((ScopeMetadataResolver)BeanUtils.instantiateClass(resolverClass));
}

    scanner.setResourcePattern(componentScan.getString("resourcePattern"));
    //設(shè)置ComponentScan對(duì)象的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);
        }
    }
    //設(shè)置ComponentScan對(duì)象的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<String> 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);
        }
    });
    //真正的進(jìn)行掃描解析
    return scanner.doScan(StringUtils.toStringArray(basePackages));
}
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI