Springboot启动源码初学

Springboot启动源码初学

1、调用静态方法run()

public static void main(String[] args) {
		SpringApplication.run(SpringbootdemoApplication.class, args);
		logger.info("Application启动完成!");
	}
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
        return run(new Class[]{primarySource}, args);
    }
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
        return (new SpringApplication(primarySources)).run(args);
    }

2、调用SpringApplication构造方法,生成实例。

在这个过程中会调用构造方法内部的initialize()方法,该方法通过getSpringFactoriesInstance()方法初始化ApplicationContextInitializer和ApplicationListener对象实例。
public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
        this.sources = new LinkedHashSet();
        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.lazyInitialization = false;
        this.resourceLoader = resourceLoader;
        Assert.notNull(primarySources, "PrimarySources must not be null");
        this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
        this.webApplicationType = WebApplicationType.deduceFromClasspath();
        this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
        this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
        this.mainApplicationClass = this.deduceMainApplicationClass();
    }

3、调用SpringApplication的实例方法run()

public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
        return (new SpringApplication(primarySources)).run(args);
    }
public ConfigurableApplicationContext run(String... args) {
        //时间监控,实例化StopWatch并开始计时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
        //java.awt.headless是J2SE的一种模式用于在缺少显示屏、键盘或者鼠标时的系统配置,很多监控工具如jconsole 需要将该值设置为true,系统变量默认为true
        this.configureHeadlessProperty();
        //第一步:获取并启动监听器。
        //获取SpringApplicationRunListener对象
        //同样通过getSpringFactoriesInstances方法从META-INF/sping.factories中获取SpringApplicationRunListener实例列表
        SpringApplicationRunListeners listeners = this.getRunListeners(args);
        //触发starting()方法
        listeners.starting();
        Collection exceptionReporters;
        try {
        	//该类对传入的args参数进行封装解析
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            //构建容器环境,并初始化配置
            ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
            this.configureIgnoreBeanInfo(environment);
            //读取配打印配置的banner,返回一个PrintedBanner对象
            Banner printedBanner = this.printBanner(environment);
            //根据environment的值创建响应类型的context
            //返回AnnotationConfigEmbeddedWebApplicationContext或者AnnotationConfigApplicationContext
            context = this.createApplicationContext();
            exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
            //预配置context
            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) {
		//该方法通过webEnviroment的值进行判断是否为web环境,如果是web环境,返回StandardServletEnvironment,不是web环境,返回StandardEnvironment。
        ConfigurableEnvironment environment = this.getOrCreateEnvironment();
        this.configureEnvironment((ConfigurableEnvironment)environment, applicationArguments.getSourceArgs());
        //配置属性源到environment中
        //首先将默认的属性map放进去,如果map为空,则不放,然后将启动参数args放进去,如果为空,则不放。
        //若两者都为空,不作处理,直接返回。
        ConfigurationPropertySources.attach((Environment)environment);
        //发布environmentPrepared事件,该事件会调用BootstrapApplicationListener,该Listener会对environment进行初始化操作,例如读取配置的profile。
        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;
    }
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
        context.setEnvironment(environment);
        //如果有,往context的factory中注入internalConfigurationBeanNameGenerator实例;
        //如果有,往context中注入GenericApplicationContext、DefaultResourceLoader
        this.postProcessApplicationContext(context);
        //根据前面获取到的ApplicatonContextInitializer实例列表,并根据order排序。
        //判断Initializer的父类的泛型与context的类型是否一致
        //迭代Initializer实例,调用initializer.initialize(context)对context进行初始化。
        this.applyInitializers(context);
        //发布contextPrepare事件
        listeners.contextPrepared(context);
        if (this.logStartupInfo) {
            this.logStartupInfo(context.getParent() == null);
            this.logStartupProfileInfo(context);
        }

        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //注册单例对象springApplicationArguments
        beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
        if (printedBanner != null) {
        //注册单例对象springBootBanner
            beanFactory.registerSingleton("springBootBanner", printedBanner);
        }

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

        if (this.lazyInitialization) {
            context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
        }

        Set<Object> sources = this.getAllSources();
        Assert.notEmpty(sources, "Sources must not be empty");
        //加载spring配置类的名称到工厂的beanDefinationNames属性,该属性是一个ArrayList
        this.load(context, sources.toArray(new Object[0]));
        //发布contextLoaded到context对象
        listeners.contextLoaded(context);
    }

第一步:获取并启动容器

第二步:构造容器环境

第三步:创建容器

第四步:实例化SpringBootExceptionReporter.class,用来支持报告关于启动的错误

第五步:准备容器

第六步:刷新容器,刷新容器后的扩展接口

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值