Spring源码解析

通过 new RuntimeException().getStackTrace() 从方法调用栈的栈帧 StackTraceElement 里面来找到主启动类

执行流程

// 获取initializer, 排序
SpringApplication application = new SpringApplication(primaryClass);

application.run();

// 利用前面分类好的bootstrapInitializer来初始化DefaultBootstrapContext
createBootstrapContext();

// 为系统变量 SYSTEM_PROPERTY_JAVA_AWT_HEADLESS 设置默认值为 "true"
configureHeadlessProperty();

SpringApplicationRunListeners listeners = new SpringApplicationRunListeners();

// 比较复杂, 暂时略过
listeners.starting(bootstrapContext, this.mainApplicationClass);

// Servlet方式, 非WebFlux方式
ConfigurableEnvironment environment = new ApplicationServletEnvironment();

// 类型转换器的设置(核心方法)
ApplicationConversionService conversionService = new ApplicationConversionService();

// 添加各种类型转换器和类型转换器工厂, GenericConversionService
conversionService.addConverterFactory(converterFactory);

// 获取factory上的两个泛型: FromType 和 ToType
ResolvableType[] typeInfo = getRequiredTypeInfo(factory.getClass(), ConverterFactory.class);
addConverter(new ConverterFactoryAdapter(factory, new ConvertiblePair(typeInfo[0].toClass(), typeInfo[1].toClass())));

ConverterFactory、ConvertiblePair 和 Converter 类

  • ConverterFactory 通过调用 getConverter() 来获取具体的 Converter
  • ConvertiblePair 封装 ConverterFactory 中的两个泛型:sourceType 和 targetType
final class NumberToNumberConverterFactory implements ConverterFactory<Number, Number>, ConditionalConverter {

    @Override
    public <T extends Number> Converter<Number, T> getConverter(Class<T> targetType) {
        return new NumberToNumber<>(targetType);
    }

    // Integer没有必要转换成Integer
    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        return !sourceType.equals(targetType);
    }


    private static final class NumberToNumber<T extends Number> implements Converter<Number, T> {

        private final Class<T> targetType;

        NumberToNumber(Class<T> targetType) {
            this.targetType = targetType;
        }

        @Override
        public T convert(Number source) {
            return NumberUtils.convertNumberToTargetClass(source, this.targetType);
        }
    }

}

ResolvableType 类


   转载规则


《Spring源码解析》 熊水斌 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
Spring Data Spring Data
Spring DataSpring Data JPA查询方式查询方式有五种: 调用父接口中的方法 方法命名规则查询(按照一定的规范定义接口中的方法, 自动生成SQL) JPQL查询 本地SQL查询 Specification动态查询 多
2023-05-05
下一篇 
图深度学习第1章 绪论1.1 图深度学习的动机 为什么要将现实数据表示为图? 为什么要将深度学习与图联系起来? 图深度学习面临哪些挑战? 为什么要将现实数据表示为图?现实世界应用产生的数据可以有多种表示形式:矩阵、张量、序列等。将数据
2023-04-20
  目录