美文网首页
Springboot启动流程源码(一)

Springboot启动流程源码(一)

作者: Zhuang_ET | 来源:发表于2019-11-04 18:53 被阅读0次

    写在前面

    Springboot对Spring做了很好的封装,仅通过添加依赖,以及一些有必要的配置外,就能够完成项目的启动。下面我将通过对一个简单的项目进行调试追踪,来发现Springboot是怎样完成一个项目的启动的。

    启动项目

    SpringApplication.run()作为项目启动的唯一入口,接下来就到SpringApplication类中查看该方法执行哪些事。

    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);
        }
    

    可以看到,通过将启动类的class对象作为参数传进来,通过SpringApplicatioin构造方法新建一个对象,再调用其run方法。本篇先介绍SpringApplication对象的新建过程,下一篇再对run方法进行介绍。

    SpringApplication

    public SpringApplication(Class<?>... primarySources) {
            this((ResourceLoader)null, primarySources);
        }
    
    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();
        }
    

    主要看关键的几步,首先是this.webApplicationType = WebApplicationType.deduceFromClasspath();这一步是推断应用类型。判断出是servlet、reactive、还是none。这一步比较好理解,就不从源码上进行分析了。

    设置初始化器

    第二步是设置初始化器,即setInitializers()方法,该方法又通过getSpringFactoriesInstances()方法进行设置。理解了getSpringFactoriesInstances()方法,就能理解设置初始化器的过程。以下是getSpringFactoriesInstances()方法的源码。

    private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
            ClassLoader classLoader = this.getClassLoader();
            Set<String> names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
            List<T> instances = this.createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
            AnnotationAwareOrderComparator.sort(instances);
            return instances;
        }
    

    在这一步里,通过类加载器去读取factoryNames,再通过factoryNames构建factory实例。

    1. 读取factoryNames
    public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
            String factoryTypeName = factoryType.getName();
            return (List)loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
        }
    
    private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
            MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
            if (result != null) {
                return result;
            } else {
                try {
                    Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
                    LinkedMultiValueMap result = new LinkedMultiValueMap();
    
                    while(urls.hasMoreElements()) {
                        URL url = (URL)urls.nextElement();
                        UrlResource resource = new UrlResource(url);
                        Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                        Iterator var6 = properties.entrySet().iterator();
    
                        while(var6.hasNext()) {
                            Entry<?, ?> entry = (Entry)var6.next();
                            String factoryTypeName = ((String)entry.getKey()).trim();
                            String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
                            int var10 = var9.length;
    
                            for(int var11 = 0; var11 < var10; ++var11) {
                                String factoryImplementationName = var9[var11];
                                result.add(factoryTypeName, factoryImplementationName.trim());
                            }
                        }
                    }
    
                    cache.put(classLoader, result);
                    return result;
                } catch (IOException var13) {
                    throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);
                }
            }
        }
    

    loadSpringFactories()这个方法会到org.springframework.boot的jar包中读取所有的META-INF/spring.factories里面的内容。比如下面是spring-boot.jar包其中的Application Context Initializers内容:

    # Application Context Initializers
    org.springframework.context.ApplicationContextInitializer=\
    org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
    org.springframework.boot.context.ContextIdApplicationContextInitializer,\
    org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
    org.springframework.boot.rsocket.context.RSocketPortInfoApplicationContextInitializer,\
    org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer
    

    读取这些文件后将内容以键值对的形式存储到Map<String, List<String>>中。通过该方法读取了# Application Context Initializers、# Application Listeners、# Environment Post Processors等等这样一些写在spring.factories文件中的factoryNames。再通过传给loadFactoryNames()方法的Class<?> factoryType参数筛选出相对应的factoryNames,即以Map的键名读取值。回到setInitializers()方法,传入的参数为ApplicationContextInitializer.class,因此获取到的便是ApplicationContextInitializers的factoryNames。

    2. 构建factory实例

    通过createSpringFactoriesInstances()方法构建factory实例,该方法的代码如下:

    private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args, Set<String> names) {
            List<T> instances = new ArrayList(names.size());
            Iterator var7 = names.iterator();
    
            while(var7.hasNext()) {
                String name = (String)var7.next();
    
                try {
                    Class<?> instanceClass = ClassUtils.forName(name, classLoader);
                    Assert.isAssignable(type, instanceClass);
                    Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
                    T instance = BeanUtils.instantiateClass(constructor, args);
                    instances.add(instance);
                } catch (Throwable var12) {
                    throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, var12);
                }
            }
    
            return instances;
        }
    

    可以看到,这一步就是根据上一步得到的factory类名,通过反射机制创建factory实例。

    设置监听器

    setListeners()方法与setInitializers()方法类似,通过传入ApplicationListener.class对象,从META-INF/spring.factories中读取相应的ApplicationListener的factoryNames。再利用反射机制对这些factory进行实例化。需要指出的是,在loadSpringFactories()方法中,由于setInitializers()方法调用了一次并将结果存入cache中,因此setListeners()方法再次调用时会将cache中保存的结果直接返回。

    推断主应用类

    deduceMainApplicationClass()方法通过跟踪栈轨迹,找出main方法所在的类,进而推断出我们项目的主应用类。代码如下:

    private Class<?> deduceMainApplicationClass() {
            try {
                StackTraceElement[] stackTrace = (new RuntimeException()).getStackTrace();
                StackTraceElement[] var2 = stackTrace;
                int var3 = stackTrace.length;
    
                for(int var4 = 0; var4 < var3; ++var4) {
                    StackTraceElement stackTraceElement = var2[var4];
                    if ("main".equals(stackTraceElement.getMethodName())) {
                        return Class.forName(stackTraceElement.getClassName());
                    }
                }
            } catch (ClassNotFoundException var6) {
            }
    
            return null;
        }
    

    总结

    回顾一下内容,首先,启动项目分为两步:创建SpringApplication对象、调用SpringApplication对象的run()方法。创建SpringApplication对象主要有四步:判断应用类型、设置初始化器、设置监听器、判断主应用类。其中设置初始化器和监听器都通过类加载器去读取jar包中的META-INF/spring.factories文件,存储到Map中,然后再通过反射机制完成factory的实例化。这就是SpringApplication对象创建过程完成的工作。下一篇我将对run()方法进行介绍。

    相关文章

      网友评论

          本文标题:Springboot启动流程源码(一)

          本文链接:https://www.haomeiwen.com/subject/hfhpsctx.html