SpringBoot2_简单原理分析

1.讲解

我们每添加一个starter,就相当于往spring容器里增加了相关功能的类,后续我们就可以直接使用每个starter提供的功能,比如当前添加了web方面的starter

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.15.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

启动

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

1.1 注解分析

在这里插入图片描述

1.1.1 @SpringBootApplication

SpringBoot注解

@Target(ElementType.TYPE)            // 注解的适用范围,其中TYPE用于描述类、接口(包括包注解类型)或enum声明
@Retention(RetentionPolicy.RUNTIME)  // 注解的生命周期,保留到class文件中(三个生命周期)
@Documented                          // 表明这个注解应该被javadoc记录
@Inherited                           // 子类可以继承该注解
@SpringBootConfiguration             // 继承了Configuration,表示当前是注解类
@EnableAutoConfiguration             // 开启springboot的注解功能,springboot的四大神器之一,其借助@import的帮助
@ComponentScan(    // 扫描路径设置( 默认会扫描当前 package 下的的所有加了@Component 、@Repository、@Service、@Controller的类到 IoC 容器中)
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {

1.1.2 @SpringBootConfiguration

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}

1.从源码可知,@SpringBootConfiguration其实就是表示一个配置的注解,这个注解,只是@Configuration注解的派生注解,跟@Configuration注解的功能一致,标注这个类是一个配置类,只不过@SpringBootConfiguration是springboot的注解,而@Configuration是spring的注解
2.一般这个注解和@Bean一起使用,就可以把需要增加的类通过@Bean来加入到spring容器中

1.1.3 @ComponentScan

spring注解 @ComponentScan,@ComponentScans 以及@Filter的使用

1.1.4 @EnableAutoConfiguration

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    Class<?>[] exclude() default {};

    String[] excludeName() default {};
}
  • Spring框架提供的各种名字为@Enable开头的Annotation定义,比如@EnableScheduling、@EnableCaching、@EnableMBeanExport等,@EnableAutoConfiguration的理念和做事方式其实一脉相承,简单概括一下就是,借助@Import的支持,收集和注册特定场景相关的bean定义

  • 如果需要设置自动配置的话,方法是将@EnableAutoconfiguration注解添加到您的@configuration类中。

1.1.5 @AutoConfigurationPackage

  • @AutoConfigurationPackage的作用相似于
<context:component-scan base-package="com.zy"/>
  • AutoConfigurationPackage注解的作用是将 添加该注解的类所在的package 作为 自动配置package 进行管理。当SpringBoot应用启动时默认会将启动类所在的package作为自动配置的package

  • 结合@ComponentScan,自动注入主类下所在包下(com.zy),所有的加了注解的类(@Controller,@Service等),以及配置类(@Configuration)

//向容器中注入一个Registrar实例
@Import({Registrar.class})
public @interface AutoConfigurationPackage {
}
	//一个内部类,实现了ImportBeanDefinitionRegistrar接口
    static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
        Registrar() {
        }
		//注册操作,注册一个GenericBeanDefinition类实例,这个实例indexedArgumentValues第一个值为com.zy
        public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        	//AutoConfigurationPackages.PackageImport(metadata) 其实返回了当前主程序类的包路径
            AutoConfigurationPackages.register(registry, (new AutoConfigurationPackages.PackageImport(metadata)).getPackageName());
        }

在这里插入图片描述

在这里插入图片描述
GenericBeanDefinition及其子类
了解Spring之BeanDefinition对象

1.1.6 @Import({AutoConfigurationImportSelector.class})

  • @Import可以导入bean或者@Configuration修饰的配置类。如果配置类在标准的springboot的包结构下,就是SpringbootApplication启动类在包的根目录下,配置类在子包下。就不需要使用@Import导入配置类,如果配置类在第三方的jar下,我们想要引入这个配置类,就需要@Import对其引入到工程中才能生效。因为这个时候配置类不再springboot默认的扫描范围内。另外,@Import 相当于Spring xml配置文件中的<import /> 标签。 参考:Springboot2 注解@Import的使用

  • @import,这个主要可以用来导入第三方jar包使用的,比如我们平时用的starter,只要里面在META-INFO配置了配置文件,那么一样会自动加载到我们Spring容器中来

  • {AutoConfigurationImportSelector.class}:导入AutoConfigurationImportSelector类到容器中

  • AutoConfigurationImportSelector 确定了导入哪些组件到选择器。该类中有个方法 selectImports,返回了一个 String 数组,其中内容就是需要导入的组件的全类名,这些组件会被自动添加到 Spring 容器。

如下,当SpringBoot启动后,初始化init或者refresh的时候,就会调用getAutoConfigurationEntry方法,从spring-autoconfigure-metadata.properties或者META-INF/spring.factories路径下获取配置信息,然后查看其ConditionalOnClass或者ConditionalOnProperty(也就是@Conditon类型的注解)是否满足,满足才会对其进行自动注入
参考: springboot的自动配置原理

	protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
			AnnotationMetadata annotationMetadata) {
		if (!isEnabled(annotationMetadata)) {
			return EMPTY_ENTRY;
		}
		AnnotationAttributes attributes = getAttributes(annotationMetadata);
		//获取配置
		List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
		configurations = removeDuplicates(configurations);
		Set<String> exclusions = getExclusions(annotationMetadata, attributes);
		checkExcludedClasses(configurations, exclusions);
		configurations.removeAll(exclusions);
		configurations = filter(configurations, autoConfigurationMetadata);
		fireAutoConfigurationImportEvents(configurations, exclusions);
		return new AutoConfigurationEntry(configurations, exclusions);
	}

getCandidateConfigurations(获取候选配置):这个方法,就是获取配置文件中规定需要加载的全名称类

	protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
		List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
				getBeanClassLoader());
		Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
				+ "are using a custom packaging, make sure that file is correct.");
		return configurations;
	}

loadFactoryNames:此方法,就是会遍历所有META-INFO下面的相关配置文件,并读取到内存中来

    public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
        String factoryClassName = factoryClass.getName();
        return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
    }

在这里插入图片描述

此处,遍历所有jar包classpath中搜寻所有的META-INF/spring.factories配置文件,并将其中org.springframework.boot.autoconfigure.EnableutoConfiguration对应的配置项通过反射(Java Refletion)实例化为对应的标注了@Configuration的JavaConfig形式的IoC容器配置类,然后汇总为一个并加载到IoC容器(加载的时候,会通过一些filter来过滤XXonCondition注解,只有满足Condition的类才会生成到内存中),并读取出来,同时,把相关内容放到缓存cache中

    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 factoryClassName = ((String)entry.getKey()).trim();
                        String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
                        int var10 = var9.length;

                        for(int var11 = 0; var11 < var10; ++var11) {
                            String factoryName = var9[var11];
                            result.add(factoryClassName, factoryName.trim());
                        }
                    }
                }

                cache.put(classLoader, result);
                return result;
            } catch (IOException var13) {
                throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);
            }
        }
    }

在这里插入图片描述

1.1.7 后续待定…

1.2 代码分析

1.2.1 SpringApplication

1.执行SpringApplication.run方法后,会给我们返回一个ConfigurableApplicationContext对象,这个对象就是Spring上下文,我们可以从这个对象获取已经注入到Spring容器中的所有Bean

    public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
        return (new SpringApplication(primarySources)).run(args);
    }

2.new SpringApplication(primarySources):其实返回的是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.resourceLoader = resourceLoader;
        Assert.notNull(primarySources, "PrimarySources must not be null");
        this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
        this.webApplicationType = WebApplicationType.deduceFromClasspath();
        //参数是ApplicationContextInitializer,则从配置文件中查找org.springframework.context.ApplicationContextInitializer标记的所有配置类
        this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
        //同理,参数是ApplicationListener,则查找applicationListener相关的类
        this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
        this.mainApplicationClass = this.deduceMainApplicationClass();
    }

WebApplicationType.deduceFromClasspath():判断是否为web应用。通过判断webflux相关的类是否存在,存在则认为是REACTIVE类型,不存在继续判断servlet相关的类是否存在,都存在则认为是SERVLET类型,都不存在则认为是NONE类型。

    static WebApplicationType deduceFromClasspath() {
        if (ClassUtils.isPresent("org.springframework.web.reactive.DispatcherHandler", (ClassLoader)null) && !ClassUtils.isPresent("org.springframework.web.servlet.DispatcherServlet", (ClassLoader)null) && !ClassUtils.isPresent("org.glassfish.jersey.servlet.ServletContainer", (ClassLoader)null)) {
            return REACTIVE;
        } else {
            String[] var0 = SERVLET_INDICATOR_CLASSES;
            int var1 = var0.length;

            for(int var2 = 0; var2 < var1; ++var2) {
                String className = var0[var2];
                if (!ClassUtils.isPresent(className, (ClassLoader)null)) {
                    return NONE;
                }
            }

            return SERVLET;
        }
    }

获取相关配置类实例

    private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
        ClassLoader classLoader = this.getClassLoader();
        //获取初始化配置信息,比如type传递的是org.springframework.context.ApplicationContextInitializer,则获取这个key下的所有初始化类
        Set<String> names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
        List<T> instances = this.createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
        AnnotationAwareOrderComparator.sort(instances);
        return instances;
    }

在这里插入图片描述

createSpringFactoriesInstances()方法中,通过反射的方式创建出各ApplicationContextInitializer所有实现类的实例,然后添加到List中返回。setInitializers()方法最终完成SpringApplication类中initializers变量的注入

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

1.2.2 ConfigurableApplicationContext

    public ConfigurableApplicationContext run(String... args) {
    	//记录程序运行时间
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        //Spring 应用的上下文
        ConfigurableApplicationContext context = null;
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
        this.configureHeadlessProperty();
        // 获取 SpringApplicationRunListeners
        SpringApplicationRunListeners listeners = this.getRunListeners(args);
        listeners.starting();

        Collection exceptionReporters;
        try {
        	// 创建 ApplicationArguments 对象
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            // 加载属性配置
            ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
            // 处理需要忽略的Bean
            this.configureIgnoreBeanInfo(environment);
            // 打印 banner
            Banner printedBanner = this.printBanner(environment);
            // 创建 Spring 应用上下文
            context = this.createApplicationContext();
            // 实例化 SpringBootExceptionReporter,用来报告关于启动过程中的错误
            exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
            // 应用上下文的准备阶段
            this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            // 刷新应用上下文(自动装配,初始化 IOC 容器)
            this.refreshContext(context);
            this.afterRefresh(context, applicationArguments);
            stopWatch.stop();
            if (this.logStartupInfo) {
                (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
            }

            listeners.started(context);
            this.callRunners(context, applicationArguments);
        } catch (Throwable var10) {
            this.handleRunFailure(context, var10, exceptionReporters, listeners);
            throw new IllegalStateException(var10);
        }

        try {
            listeners.running(context);
            return context;
        } catch (Throwable var9) {
            this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
            throw new IllegalStateException(var9);
        }
    }

1.2.3 后续待定…

2.其他

参考

一文搞懂springboot启动原理
springboot核心原理
SpringBoot 2.X课程学习 | 第三篇:自动配置(Auto-configuration)
【SpringBoot】自动配置原理解析
springboot初学(二)EnableAutoConfigurationImportSelector

SpringApplication.run 到底做了什么?
SpringApplication.run执行流程详解
SpringBoot启动流程分析(二):SpringApplication的run方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值