SpringBoot系列—Run启动原理(十八)

个人博客:haichenyi.com。感谢关注

  需要搞清楚几个重要的事件回调机制

配置在META-INF/spring.factories

  • ApplicationContextInitializer
  • SpringApplicationRunListener

只需要放在ioc容器中

  • ApplicationRunner

  • CommandLineRunner

  新建一个空项目,就勾选web,找到启动类,每个方法上面写的注释,可以看一下:

@SpringBootApplication
public class SellApplication {

    public static void main(String[] args) {
        SpringApplication.run(SellApplication.class, args);
    }

}

//上面run方法点进来
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);
    }
    

看到这里,就应该看到了,启动流程分为两步

  1. 创建SpringApplication对象
  2. 运行run方法

创建SpringApplication对象

//上面的构造方法点进去
//这里与1.5版本不一样的地方就是,
//2.X这里调用了重载的构造方法,而1.5这里调用的是一个initialize()方法,这个方法里面的内容,与下面两个参数的重载方法差不多
public SpringApplication(Class... primarySources) {
        this(null, primarySources);
    }

//下面这个就是this调用的重载的构造方法
@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
        this.resourceLoader = resourceLoader;
        //保存主配置类,1.5里面这里有个非空判断,用if做的,这里换成的断言做判断
        Assert.notNull(primarySources, "PrimarySources must not be null");
        this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
        //判断当前是否一个web应用
        this.webApplicationType = WebApplicationType.deduceFromClasspath();
        //从类路径下找到META‐INF/spring.factories配置的所有ApplicationContextInitializer;然后保存起 来
        setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
        //从类路径下找到ETA‐INF/spring.factories配置的所有ApplicationListener
        setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
        //从多个配置类中找到有main方法的主配置类
        this.mainApplicationClass = deduceMainApplicationClass();
    }

setInitializers()方法

  看方法名就知道,这个是初始化方法,初始化什么东西呢?再看传的参数ApplicationContextInitializer,就是一开始我们提到的类。我们看这个是怎么获取的

//第一步:
private SpringApplicationRunListeners getRunListeners(String[] args) {
        Class[] types = new Class[] { SpringApplication.class, String[].class };
        return new SpringApplicationRunListeners(logger,
                getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
}

//第二步:
private  Collection getSpringFactoriesInstances(Class type, Class[] parameterTypes, Object... args) {
        ClassLoader classLoader = getClassLoader();
        // Use names and ensure unique to protect against duplicates
        //看这里的导入方法SpringFactoriesLoader.loadFactoryNames(type, classLoader)
        Set names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
        List instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
        AnnotationAwareOrderComparator.sort(instances);
        return instances;
    }
    
//第三步:
public static List loadFactoryNames(Class factoryType, @Nullable ClassLoader classLoader) {
        String factoryTypeName = factoryType.getName();
        return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
    }

//第四步,就是这里了。看这里面的实现
private static Map> loadSpringFactories(@Nullable ClassLoader classLoader) {
        MultiValueMap result = cache.get(classLoader);
        if (result != null) {
            return result;
        }

        try {
        //一眼看过去。很明显,这里就是classLoader.getResources(),导入的本地的资源。看这个传的参数,我放到这个方法下面去了
            Enumeration urls = (classLoader != null ?
                    classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
                    ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
            result = new LinkedMultiValueMap<>();
            //这里通过一个while循环,加载本地配置的ApplicationContextInitializer
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                UrlResource resource = new UrlResource(url);
                Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                for (Map.Entry entry : properties.entrySet()) {
                    String factoryTypeName = ((String) entry.getKey()).trim();
                    for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
                        result.add(factoryTypeName, factoryImplementationName.trim());
                    }
                }
            }
            cache.put(classLoader, result);
            return result;
        }
        catch (IOException ex) {
            throw new IllegalArgumentException("Unable to load factories from location [" +
                    FACTORIES_RESOURCE_LOCATION + "]", ex);
        }
    }
    
/**
 * The location to look for factories.
 * 

Can be present in multiple JAR files. */ public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

  所以,从上面的源码,我们一步一步点击进去看,我们就能发现,他最终都是加载到 META-INF/spring.factories 目录下的 ApplicationContextInitializer 当然,到目前为止这里只是初始化

setListeners()方法

  一眼就能看出来,这里是设置监听方法

setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));

  一眼看过去,这个setListener方法传的参数熟不熟悉?就是我们上面初始化的时候传的参数是同一个方法。所以,这里设置监听设置哪些监听方法也是META-INF/spring.factories 目录下的listener方法,我们看一下这个文件内容:

SpringBoot系列—Run启动原理(十八)_第1张图片
spring_factories.png

  这些都是是自动配置类的内容

运行Run方法

public ConfigurableApplicationContext run(String... args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        Collection exceptionReporters = new ArrayList<>();
        configureHeadlessProperty();
        //获取SpringApplicationRunListeners;从类路径下META‐INF/spring.factories
        SpringApplicationRunListeners listeners = getRunListeners(args);
        //回调所有的获取SpringApplicationRunListener.starting()方法
        listeners.starting();
        try {
            //封装命令行参数
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            //准备环境,创建环境完成后回调SpringApplicationRunListener.environmentPrepared();表示环境准 备完成
            ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
            //这里是新增的,点击去看,就是再properties文件中配置你需要忽略的bean
            configureIgnoreBeanInfo(environment);
            //这个是打印spring的logo banner图
            Banner printedBanner = printBanner(environment);
            /创建ApplicationContext;这个下面有下介绍
            context = createApplicationContext();
            //看一下参数,这个就是做异常报告处理的
            exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                    new Class[] { ConfigurableApplicationContext.class }, context);
                    
            //准备上下文环境;将environment保存到ioc中;而且applyInitializers();
            //applyInitializers():回调之前保存的所有的ApplicationContextInitializer的initialize方法
            //回调所有的SpringApplicationRunListener的contextPrepared();  
            //prepareContext运行完成以后回调所有的SpringApplicationRunListener的contextLoaded();
            prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            //s刷新容器;ioc容器初始化(如果是web应用还会创建嵌入式的Tomcat);Spring注解版
            //扫描,创建,加载所有组件的地方;(配置类,组件,自动配置)
            refreshContext(context);
            //2.x里面是空方法
            afterRefresh(context, applicationArguments);
            stopWatch.stop();
            if (this.logStartupInfo) {
                new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
            }
            listeners.started(context);
            
            //从ioc容器中获取所有的ApplicationRunner和CommandLineRunner进行回调 //ApplicationRunner先回调,CommandLineRunner再回调
            callRunners(context, applicationArguments);
        }
        catch (Throwable ex) {
            handleRunFailure(context, ex, exceptionReporters, listeners);
            throw new IllegalStateException(ex);
        }

        try {
            listeners.running(context);
        }
        catch (Throwable ex) {
            handleRunFailure(context, ex, exceptionReporters, null);
            throw new IllegalStateException(ex);
        }
        //返回这个IOC容器
        return context;
    }

getRunListeners()方法

  我们看到上面第一个有注释的位置:getRunListeners方法

private SpringApplicationRunListeners getRunListeners(String[] args) {
        Class[] types = new Class[] { SpringApplication.class, String[].class };
        return new SpringApplicationRunListeners(logger,
                getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
}

  方法熟悉吗?就是我们上面初始化的时候调用的那个方法,只是这里的参数传的是:SpringApplicationRunListener,我们看最开始说的,这就是我们要了解的第二个内容,回调都是怎么调用的

  方法里面的注释也写了,先获取监听事件,然后回调starting方法,我们看一下这个接口有那些回调方法:

public interface SpringApplicationRunListener {

    default void starting() {
    }
    
    default void environmentPrepared(ConfigurableEnvironment environment) {
    }
    
    default void contextPrepared(ConfigurableApplicationContext context) {
    }

    default void contextLoaded(ConfigurableApplicationContext context) {
    }

    default void started(ConfigurableApplicationContext context) {
    }

    default void running(ConfigurableApplicationContext context) {
    }

    default void failed(ConfigurableApplicationContext context, Throwable exception) {
    }

}

  就这些回调,这里还用了1.8的新特性,default关键字,接口里面的方法可以有方法体

prepareEnvironment()

  看到第二个写注释的位置,眼熟吗?可不就是跟上面回调方法名字相同么?我们点进去看一下

private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
            ApplicationArguments applicationArguments) {
        // Create and configure the environment
        ConfigurableEnvironment environment = getOrCreateEnvironment();
        configureEnvironment(environment, applicationArguments.getSourceArgs());
        ConfigurationPropertySources.attach(environment);
        
        //这里划重点,这里就调用的environmentPrepared的回调方法
        listeners.environmentPrepared(environment);
        bindToSpringApplication(environment);
        if (!this.isCustomEnvironment) {
            environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
                    deduceEnvironmentClass());
        }
        ConfigurationPropertySources.attach(environment);
        return environment;
    }

  准备完环境之后,调用environmentPrepared的回调

createApplicationContext()

protected ConfigurableApplicationContext createApplicationContext() {
        Class contextClass = this.applicationContextClass;
        if (contextClass == null) {
            try {
                switch (this.webApplicationType) {
                case SERVLET:
                    contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
                    break;
                case REACTIVE:
                    contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
                    break;
                default:
                    contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
                }
            }
            catch (ClassNotFoundException ex) {
                throw new IllegalStateException(
                        "Unable create a default ApplicationContext, please specify an ApplicationContextClass", ex);
            }
        }
        return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
    }

  创建applicationContext,这里跟1.5不一样,1.5就只有两种:一种是web的ioc容器,一种是默认的ioc容器。2.X这里有三种:DEFAULT_CONTEXT_CLASS,DEFAULT_SERVLET_WEB_CONTEXT_CLASS,DEFAULT_REACTIVE_WEB_CONTEXT_CLASS,实际字符串比较长,可以去看一下源码。然后用BeanUtils通过反射创建。

prepareContext()方法

private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,
            SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
        //将environment放到context中
        context.setEnvironment(environment);
        postProcessApplicationContext(context);
        //初始化
        applyInitializers(context);
        //这里回调contextPrepared方法
        listeners.contextPrepared(context);
        if (this.logStartupInfo) {
            logStartupInfo(context.getParent() == null);
            logStartupProfileInfo(context);
        }
        // Add boot specific singleton beans
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
        if (printedBanner != null) {
            beanFactory.registerSingleton("springBootBanner", printedBanner);
        }
        if (beanFactory instanceof DefaultListableBeanFactory) {
            ((DefaultListableBeanFactory) beanFactory)
                    .setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
        }
        if (this.lazyInitialization) {
            context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
        }
        // Load the sources
        Set sources = getAllSources();
        Assert.notEmpty(sources, "Sources must not be empty");
        load(context, sources.toArray(new Object[0]));
        //这里回调contextLoaded()方法
        listeners.contextLoaded(context);
    }
 
 

  准备上下文环境;将environment保存到ioc中;而且applyInitializers()

protected void applyInitializers(ConfigurableApplicationContext context) {
        for (ApplicationContextInitializer initializer : getInitializers()) {
            Class requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(),
                    ApplicationContextInitializer.class);
            Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
            initializer.initialize(context);
        }
    }

  这里就将我们一开始从配置文件里面读取,然后创建ApplicationContextInitializer初始化。

  当环境准备好之后,就回调了SpringApplicationRunListener的contextPrepared();

  当所有的都准备好了之后,回调SpringApplicationRunListener的contextLoaded();

  到这里,所有的环境都准备好了,需要打印的logo也加进去了。

refreshContext()

  刷新容器这个方法,我们可以点到具体的功能实现里面,可以看到,这里就是扫描,创建,加载所有的组件,配置类,组件,自动配置等。

  到这里,这个方法创建完之后,所有的控制器就创建完了,所有的组件,bean等,都在控制台打印出来了。如果是web应用,还会创建嵌入式的tomcat。我们spring boot项目内嵌tomcat,就是在这里创建的。

afterRefresh()

  1.5版本这个方法里面回调的是callRunners方法,而2.X版本,现在这是个空方法里面并没有实现。callRunners被提出来了,放到了最后面。

started(),running()

  在1.5版本这里,也就是afterRefresh()之后,应该是调用的SpringApplicationRunListeners的finished()方法。

  在2.X版本之后,去掉了finished方法,改成了调用started方法,然后调用running方法。我们上面有一个starting方法,从这里名字就可以看出来,相当于,首先是正在启动当中,然后就是启动完成了,正在运行了。

callRunners()

private void callRunners(ApplicationContext context, ApplicationArguments args) {
        List runners = new ArrayList<>();
        runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
        runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
        AnnotationAwareOrderComparator.sort(runners);
        for (Object runner : new LinkedHashSet<>(runners)) {
            if (runner instanceof ApplicationRunner) {
                callRunner((ApplicationRunner) runner, args);
            }
            if (runner instanceof CommandLineRunner) {
                callRunner((CommandLineRunner) runner, args);
            }
        }
    }
 
 

  从IOC容器中(不是配置文件)获取所有的的ApplicationRunner和CommandLineRunner进行回调。这也是最开始说的两个注意的地方

  并且,这里有个先后顺序,先回调的ApplicationRunner,后回调的CommandLineRunner

  这里也是run方法,最后执行的地方。从这里就是真正的开启了run。

  最后一步,返回那个context就是返回IOC容器对象。到这里,我们的spring boot就启动完成了。

  这就是我们的spring boot的启动原理。初始化,listener的回调,Runner的回调都说的很清楚。

你可能感兴趣的:(SpringBoot系列—Run启动原理(十八))