技术分享|SpringBoot 底层原理剖析

大家好,我是猿猴小冷,今天给大家分享一下SpringBoot的底层原理
一、入口类的源码解析 1. 入口类

package com.lq.consumer_user; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication public class ConsumerUserApplication {public static void main(String[] args) { SpringApplication.run(ConsumerUserApplication.class, args); }}

2. @SpringBootApplication 核心注解源码分析 Spring Boot应用标注在某个类上说明这个类是SpringBoot的主配置类,SpringBoot就应该运行这个类的main方法来启动SpringBoot应用。
主要组成:@SpringBootConfiguration,@EnableAutoConfiguration以及@ComponentScan这三个注解
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan( excludeFilters = {@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class} ), @Filter( type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class} )} ) public @interface SpringBootApplication {

a. @SpringBootConfiguration 注解 Spring Boot的配置类: 标注在某个类上,表示一个类提供了Spring Boot应用程序
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration public @interface SpringBootConfiguration {

(1) @Configuration:配置类上来标注这个注解:来标注这个类是个配置类
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Configuration {

注意:配置类相当于配置文件;配置类也是容器中的一个组件,它使用了@Component这个注解。
3. @EnableAutoConfiguration 注解 告诉SpringBoot开启自动配置功能,这样自动配置才能生效,借助@import,扫描并实例化满足条件的自动配置的bean,然后加载到IOC容器中。
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import(AutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration { String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; /** * Exclude specific auto-configuration classes such that they will never be applied. * @return the classes to exclude */ Class[] exclude() default {}; /** * Exclude specific auto-configuration class names such that they will never be * applied. * @return the class names to exclude * @since 1.3.0 */ String[] excludeName() default {}; }

@AutoConfigurationPackage:自动配置包
@Import(EnableAutoConfigurationImportSelector.class):给容器中导入组件

4. @ComponentScan 注解 【技术分享|SpringBoot 底层原理剖析】@ComponentScan就是自动扫描并加载符合条件的组件(比如@Component和@Repository等)或者bean定义,最终将这些bean定义加载到IOC容器中去 。

    推荐阅读