SpringBoot:创建SpringApplication对象

SpringBoot:创建SpringApplication对象
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }

}
1、创建 SpringApplication对象。

一路调用下来,执行到了 SpringApplication 的构造方法中。

 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));
        // 根据关键字获取当前 SpringApplication 的类型,结果是:SERVLET。
        this.webApplicationType = WebApplicationType.deduceFromClasspath();
        // 设置初始化器。
        this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
        // 设置监听器。
        this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
        // 设置主类。
        this.mainApplicationClass = this.deduceMainApplicationClass();
    }

构造器中做了什么呢?给应用程序的属性设置值。

1、设置资源加载器。

2、设定主配置类,最关键的是主配置类上的 @SpringBootApplication 注解,此处先不展开描述。

3、设置应用程序类型为 SERVLET,表示当前应用程序是内嵌了 servlet 的 web 应用程序。

4、设置初始化器。应用程序在执行 run() 方法时会创建 IOC容器(这是一个 ApplicationContext 对象),初始化器是后面用来向 IOC 容器中加载资源的。

5、设置监听器。监听器的作用是监控应用程序的运行状态,并且在一些指定状态出现时发布事件,比如:向终端打印启动时的 log。

6、设置主类。

2、引导启动器、初始化器、监听器都是怎么加载进来的。

从上面的代码可以看到,引导启动器、初始化器、监听器的加载过程是一样的,那就看看getSpringFactoriesInstances() 是怎么把这些都加载进来的。 以 设置初始化容器,this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class)) 为例。

 private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
        // 类加载器
        ClassLoader classLoader = this.getClassLoader();
        // 获取到所有 ApplicationContextInitializer.class 子类的全限定名。
        Set<String> names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
        // 使用全限定名通过反射给每个初始化器创建一个实例。并将所有实例存放到集合中。
        List<T> instances = this.createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
        // 对集合中的初始化器排序。
        AnnotationAwareOrderComparator.sort(instances);
        // 返回所有的初始化器。
        return instances;
    }

1、跟进Set names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));初始化器的全限定名怎么被加载到了内存中?

    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 {
               // try块里面的代码就做了一件事情,读全部spring.factories文件,并将其中的信息构建成键值对放到result。
                Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
                MultiValueMap<String, String> 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()) {
                        Map.Entry<?, ?> entry = (Map.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);
            }
        }
    }

2、 类的全限定名怎么反射到实例的?

  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对象。
                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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一枚尘世中迷途小书童

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值