您的位置:首页 > 编程语言 > Java开发

Spring基础系列-容器启动流程(2)

2018-08-28 12:02 661 查看

 原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9503210.html 

一、概述

  这里是Springboot项目启动大概流程,区别于SSM框架项目启动流程。

二、启动流程

  Springboot项目可以直接从main方法启动。

  源码1-来自DemoApplicaiton(应用自定义的)

1 @SpringBootApplication
2 public class DemoApplication {
3
4     public static void main(String[] args) {
5         SpringApplication.run(DemoApplication.class, args);
6     }
7 }

  首先调用的是SpringApplication中的run方法。

  源码2-来自:SpringApplication

1     public static ConfigurableApplicationContext run(Class<?> primarySource,
2             String... args) {
3         return run(new Class<?>[] { primarySource }, args);
4     }
5
6     public static ConfigurableApplicationContext run(Class<?>[] primarySources,
7             String[] args) {
8         return new SpringApplication(primarySources).run(args);
9     }

  第一个run方法会调用第二个run方法。

  在第二个run方法中有两步:

    第一步:创建SpringApplicaiton实例

    第二步:调用run方法

  首先我们先创建SpringApplication实例

  源码3-来自:SpringApplication

1     public SpringApplication(Class<?>... primarySources) {
2         this(null, primarySources);
3     }
4
5     public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
6         this.resourceLoader = resourceLoader;
7         Assert.notNull(primarySources, "PrimarySources must not be null");
8         this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
9         //判断应用类型
10         this.webApplicationType = deduceWebApplicationType();
11         //添加初始化器
12         setInitializers((Collection) getSpringFactoriesInstances(
13                 ApplicationContextInitializer.class));
14         //添加监听器
15         setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
16         //定位main方法所在类,并做记录
17         this.mainApplicationClass = deduceMainApplicationClass();
18     }

  SpringBoot应用有三种类型:

  源码4-来自:WebApplicationType

1 public enum WebApplicationType {
2
3     NONE,SERVLET,REACTIVE
4
5 }
  •   NONE:应用不是web应用,启动时不必启动内置的服务器程序
  •   SERVLET:这是一个基于Servlet的web应用,需要开启一个内置的Servlet容器(web服务器)
  •   REACTIVE:这是一个反应式web应用,需要开启一个内置的反应式web服务器

  三者的判断条件如下

  源码5-来自:SpringApplication

1     private WebApplicationType deduceWebApplicationType() {
2         if (ClassUtils.isPresent(REACTIVE_WEB_ENVIRONMENT_CLASS, null)
3                 && !ClassUtils.isPresent(MVC_WEB_ENVIRONMENT_CLASS, null)
4                 && !ClassUtils.isPresent(JERSEY_WEB_ENVIRONMENT_CLASS, null)) {
5             return WebApplicationType.REACTIVE;
6         }
7         for (String className : WEB_ENVIRONMENT_CLASSES) {
8             if (!ClassUtils.isPresent(className, null)) {
9                 return WebApplicationType.NONE;
10             }
11         }
12         return WebApplicationType.SERVLET;
13     }

  上面的方法中涉及四个常量:

  源码6-来自:SpringApplication

1     private static final String REACTIVE_WEB_ENVIRONMENT_CLASS = "org.springframework."
2             + "web.reactive.DispatcherHandler";
3
4     private static final String MVC_WEB_ENVIRONMENT_CLASS = "org.springframework."
5             + "web.servlet.DispatcherServlet";
6
7     private static final String JERSEY_WEB_ENVIRONMENT_CLASS = "org.glassfish.jersey.server.ResourceConfig";
8
9     private static final String[] WEB_ENVIRONMENT_CLASSES = { "javax.servlet.Servlet",
10             "org.springframework.web.context.ConfigurableWebApplicationContext" };

  至于代码很是简单。

  然后是设置初始化器,结合之前的讲述在SSM架构的web应用中也拥有初始化器,这两个代表的是同一个概念,不同于之前的处理方式,这里仅仅是将初始化器找到并设置到initializers属性中。

  我们来看看它是如何获取这些初始化器的:

  源码7-来自:SpringApplication、SpringFactoriesLoader

1     private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
2         return getSpringFactoriesInstances(type, new Class<?>[] {});
3     }
4
5     private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
6             Class<?>[] parameterTypes, Object... args) {
7         ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
8         // Use names and ensure unique to protect against duplicates
9         //使用指定的类加载器获取指定类型的类名集合
10         Set<String> names = new LinkedHashSet<>(
11                 SpringFactoriesLoader.loadFactoryNames(type, classLoader));
12         //创建实例
13         List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
14                 classLoader, args, names);
15         //排序
16         AnnotationAwareOrderComparator.sort(instances);
17         return instances;
18     }
19
20     下面来自:SpringFactoriesLoader
21
22     public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
23         String factoryClassName = factoryClass.getName();
24         return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
25     }
26
27     private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
28         //首先尝试从缓存获取
29         MultiValueMap<String, String> result = cache.get(classLoader);
30         if (result != null) {
31             return result;
32         }
33
34         try
35             //从META-INF/spring.factories文件中获取配置的内容
36             Enumeration<URL> urls = (classLoader != null ?
37                     classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
38                     ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
39             result = new LinkedMultiValueMap<>();
40             while (urls.hasMoreElements()) {
41                 URL url = urls.nextElement();
42                 UrlResource resource = new UrlResource(url);
43                 Properties properties = PropertiesLoaderUtils.loadProperties(resource);
44                 for (Map.Entry<?, ?> entry : properties.entrySet()) {
45                     List<String> factoryClassNames = Arrays.asList(
46                             StringUtils.commaDelimitedListToStringArray((String) entry.getValue()));
47                     result.addAll((String) entry.getKey(), factoryClassNames);
48                 }
49             }
50             //添加到缓存备用
51             cache.put(classLoader, result);
52             return result;
53         }
54         catch (IOException ex) {
55             throw new IllegalArgumentException("Unable to load factories from location [" +
56                     FACTORIES_RESOURCE_LOCATION + "]", ex);
57         }
58     }

  由此可见,初始化器是从META-INF/spring.factories文件中获取到的,那么我们就可以自建该目录文件进行添加,前提是需要自定义初始化器。

  还有这里只有在第一次调用时需要从文件读取,第二次就可以从缓存获取,哪怕需要的不是初始化器的内容,因为第一次的时候就会将所有的配置内容全部获取并解析保存到缓存备用。这也就为下一步设置监听器这一步省下了不少时间。

  最后一步就是将main方法所在类做个记录。

  源码8-来自:SpringApplication

1     private Class<?> deduceMainApplicationClass() {
2         try {
3             StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
4             for (StackTraceElement stackTraceElement : stackTrace) {
5                 if ("main".equals(stackTraceElement.getMethodName())) {
6                     return Class.forName(stackTraceElement.getClassName());
7                 }
8             }
9         }
10         catch (ClassNotFoundException ex) {
11             // Swallow and continue
12         }
13         return null;
14     }

  通过新建一个运行时异常的方式获取方法调用栈,在栈中搜索方法名为main的方法所在的类。

  如果我们想要获取方法的调用栈也可以采用这种方式,使用异常来获取调用栈。

  完成SpringApplication实例的创建之后,直接调用其run方法,执行应用启动。

  源码9-来自:SpringApplication

1     public ConfigurableApplicationContext run(String... args) {
2         StopWatch stopWatch = new StopWatch();
3         stopWatch.start();
4         ConfigurableApplicationContext context = null;
5         Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
6         //配置系统属性headless,默认为true
7         configureHeadlessProperty();
8         //获取所有的运行时监听器
9         SpringApplicationRunListeners listeners = getRunListeners(args);
10         listeners.starting();//启动监听器
11         try {
12             //封装自定义参数
13             ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
14             //根据参数配置环境environment
15             //如果是web项目则创建的是StandardServletEnvironment,否则是StandardEnvironment
16             //然后配置属性和profile
17             ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
18             //设置是否忽略BeanInfo,默认为true
19             configureIgnoreBeanInfo(environment);
20             //打印banner
21             Banner printedBanner = printBanner(environment);
22             //创建ApplicationContext
23             //如果是Servlet web项目则创建AnnotationConfigEmbeddedWebApplicationContext,如果是Reactive web
24             //项目则创建AnnotationConfigReactiveWebServerApplicationContext,否则AnnotationConfigApplicationContext
25             context = createApplicationContext();
26             //加载异常报告器
27             exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
28                 new Class[] { ConfigurableApplicationContext.class }, context);
29             //筹备上下文环境,也就是初始化
30             prepareContext(context, environment, listeners, applicationArguments, printedBanner);
31             //刷新上下文
32             refreshContext(context);
33             //刷新后操作,这是两个孔方法,是可以自定义实现逻辑的
34             afterRefresh(context, applicationArguments);
35             stopWatch.stop();
36             if (this.logStartupInfo) {
37                 new StartupInfoLogger(this.mainApplicationClass)
38                         .logStarted(getApplicationLog(), stopWatch);
39             }
40             listeners.started(context);//容器和应用启用之后,callRunner之前执行
41             //容器启动完成之后回调runner,包括:ApplicationRunner和CommandLineRunner
42             callRunners(context, applicationArguments);
43         }
44         catch (Throwable ex) {
45             handleRunFailure(context, ex, exceptionReporters, listeners);
46             throw new IllegalStateException(ex);
47         }
48
49         try {
50             listeners.running(context);
51         }
52         catch (Throwable ex) {
53             handleRunFailure(context, ex, exceptionReporters, null);
54             throw new IllegalStateException(ex);
55         }
56         return context;
57     }

  这是整个容器启动的所有逻辑入口,参照注释即可理解,我们重点关注prepareContext方法,这个方法是在容器刷新之前的预初始化操作:

  源码10-来自:SpringApplication

1     private void prepareContext(ConfigurableApplicationContext context,
2             ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
3             ApplicationArguments applicationArguments, Banner printedBanner) {
4         //设置environment到上下文
5         context.setEnvironment(environment);
6         //设置BeanName生成器
7         //设置资源加载器或者类加载器
8         postProcessApplicationContext(context);
9         //执行初始化器
10         applyInitializers(context);
11         listeners.contextPrepared(context);//执行监听器的contextPrepared操作
12         //配置日志信息
13         if (this.logStartupInfo) {
14             logStartupInfo(context.getParent() == null);
15             logStartupProfileInfo(context);
16         }
17
18         // Add boot specific singleton beans
19         //注册单例(springApplicationArguments,springBootBanner)
20         context.getBeanFactory().registerSingleton("springApplicationArguments",
21                 applicationArguments);
22         if (printedBanner != null) {
23             context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
24         }
25
26         // Load the sources
27         Set<Object> sources = getAllSources();
28         Assert.notEmpty(sources, "Sources must not be empty");
29         //加载Bean到容器
30         load(context, sources.toArray(new Object[0]));
31         //执行监听器的contextLoaded操作
32         listeners.contextLoaded(context);
33     }

  重点关注下load方法,他的目的是加载Bean定义:

  源码11-来自:SpringApplication

1     //为load操作做准备,创建资源读取器扫描器
2     protected void load(ApplicationContext context, Object[] sources) {
3         if (logger.isDebugEnabled()) {
4             logger.debug(
5                     "Loading source " + StringUtils.arrayToCommaDelimitedString(sources));
6         }
7         //创建BeanDefinition读取器,扫描器(AnnotatedBeanDefinitionReader,XmlBeanDefinitionReader,
8         //GroovyBeanDefinitionReader,ClassPathBeanDefinitionScanner)
9         BeanDefinitionLoader loader = createBeanDefinitionLoader(
10                 getBeanDefinitionRegistry(context), sources);
11         //配置BeanName生成器,资源加载器,环境参数到读取器和扫描器中
12         if (this.beanNameGenerator != null) {
13             loader.setBeanNameGenerator(this.beanNameGenerator);
14         }
15         if (this.resourceLoader != null) {
16             loader.setResourceLoader(this.resourceLoader);
17         }
18         if (this.environment != null) {
19             loader.setEnvironment(this.environment);
20         }
21         //执行Bean的加载
22         loader.load();
23     }
24
25     //统计加载Bean的数量
26     public int load() {
27         int count = 0;
28         for (Object source : this.sources) {
29             count += load(source);
30         }
31         return count;
32     }
33
34     //针对不同的情况加载bean资源
35     private int load(Object source) {
36         Assert.notNull(source, "Source must not be null");
37         //
38         if (source instanceof Class<?>) {
39             return load((Class<?>) source);
40         }
41         //Resource资源可能是XML定义的Bean资源或者groovy定义的Bean资源
42         if (source instanceof Resource) {
43             return load((Resource) source);
44         }
45         //Packet资源一般是用于注解定义的Bean资源,需要扫描器扫描包
46         if (source instanceof Package) {
47             return load((Package) source);
48         }
49         //
50         if (source instanceof CharSequence) {
51             return load((CharSequence) source);
52         }
53         throw new IllegalArgumentException("Invalid source type " + source.getClass());
54     }

  针对不同的资源进行加载。

  下面就要回到run方法中的重点操作refreshContext(context)了:

  源码12-来自:SpringApplication

1     private void refreshContext(ConfigurableApplicationContext context) {
2         refresh(context);
3         if (this.registerShutdownHook) {
4             try {
5                 context.registerShutdownHook();
6             }
7             catch (AccessControlException ex) {
8                 // Not allowed in some environments.
9             }
10         }
11     }
12
13     protected void refresh(ApplicationContext applicationContext) {
14         Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
15         ((AbstractApplicationContext) applicationContext).refresh();
16     }

  这里也到了执行refresh()方法的时候了,下面我们就要看看这个refresh了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: