SpringBoot自动配置原理

主启动类:

//@SpringBootApplication 来标注一个主程序类
//说明这是一个Spring Boot应用
@SpringBootApplication
public class StartspringbootApplication {
    //启动服务
    public static void main(String[] args) {
        SpringApplication.run(StartspringbootApplication.class, args);
    }

}

只有一个注解,说明是这个帮我们实现了自动配置。到其内部,主要三个为:

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
  • 1.@SpringBootConfiguration:我们点进去以后可以发现底层是Configuration注解,说白了就是支持JavaConfig的方式来进行配置(使用Configuration配置类等同于XML文件)。
  • //@SpringBootConfiguration注解内部
    //这里的 @Configuration,说明这是一个配置类 ,配置类就是对应Spring的xml 配置文件;
    @Configuration
    public @interface SpringBootConfiguration {}
    //里面的 @Component 这就说明,启动类本身也是Spring中的一个组件而已,负责启动应用
    @Component
    public @interface Configuration {}

  • 2.@EnableAutoConfiguration:开启自动配置功能。
  • @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 {};
    }
     

    @Import({AutoConfigurationImportSelector.class}) :给容器导入组件 ;

    AutoConfigurationImportSelector :自动配置导入选择器,给容器中导入一些组件

    AutoConfigurationImportSelector.class
    			↓
        selectImports方法
        		↓
    this.getAutoConfigurationEntry(annotationMetadata)方法
    			↓
    this.getCandidateConfigurations(annotationMetadata, attributes)方法
    			↓
    方法体:
     List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.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;
    			↓
    在所有包名叫做autoConfiguration的包下面都有META-INF/spring.factories文件

  • 3.@ComponentScan扫描注解,默认是扫描当前类下的package。将@Controller/@Service/@Component/@Repository等注解加载到IOC容器中。

总结:

        @EnableAutoConfiguration 注解内部使用 @Import(AutoConfigurationImportSelector.class)来加载配置类。

        配置文件位置:META-INF/spring.factories,该配置文件中定义了大量的配置类,当 SpringBoot 应用启动时,会自动加载这些配置类,初始化Bean。

        并不是所有的Bean都会被初始化,在配置类中使用Condition来加载满足条件的Bean。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值