SpringBoot装配原理初探

66 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第3天,点击查看活动详情

SpringBootd的核心注解:@SpringBootApplication,加上这个注解后就可以正常启动服务了。那么这个注解为什么这么强大,接下我们一起来掀开它神秘的面纱,看看SpringBoot是如何进行自动配置和启动的。

SpringBoot通过main方法启动SpringApplication类的静态方法run()启动项目。

image.png

我们可以看到该方法使用了默认配置的指定资源启动了一个SpringApplciation并返回ApplicationCOntext对象。

image.png

注解组成

@SpringBootApplication由三个注解组成分别是:@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan

1、@ComponentScan是Spring的扫描注解,默认扫描当前类所在的包及其子包下包含的注解,将@Controller/@Service/@Component/@Repository等注解加载到IOC容器中;

2、@SpringBootConfiguration:这个注解的底层是一个@Configuration注解,意思被@Configuration注解修饰的类是一个IOC容器,支持JavaConfig的方式来进行配置;

这里为了指定程序中redis序列化的方式,我们可以使用@Configuration和@Bean个性化配置redisTemple指定我们需要的序列化方式

image.png

3、@EnableAutoConfiguration:这个注解表明启动自动装配,里面包含连个比较重要的注解@AutoConfigurationPackage和@Import。

image.png

先来看@AutoConfigurationPackage,我们通过源码可以得出他和@ComponentScan一样,也是将卓配置类所在的包及其子包里面的组件扫描到IOC容器中。值得注意的是@ComponentScan只扫描@Entity、@MapperScan等第三方依赖注解。@ComponentScan只扫描@Controller、@Service、@Component、@Repository这些常见注解。所以这两个注解扫描的对象是不一样的。

image.png

@Import(AutoConfigurationImportSelector.class)是自动装配的核心注解,AutoConfigurationImportSelector.class中有个selectImports方法

image.png

selectImports方法还调用了getCandidateConfigurations方法

image.png

image.png

image.png

最终,@EnableAutoConfiguration注解通过@SpringBootApplication注解被间接的标记在了SpringBoot的启动类上,SpringApplicaton.run方法的内部就会执行selectImports方法,进而找到所有JavaConfig配置类全限定名对应的class,然后将所有自动配置类加载到IOC容器中。 那么这些类是如何获取默认属性值的呢?以ServletWebServerFactoryAutoConfiguration为例,它是Servlet容器的自动配置类

image.png 该类上开启了@EnableConfigurationProperties(ServerProperties.class)注解,最终找到了ServerProperties类。至此,我们大致可以了解。在全局配置的属性如:server.port等,通过@ConfigurationProperties注解,绑定到对应的XxxxProperties配置实体类上封装为一个bean,然后再通过@EnableConfigurationProperties注解导入到Spring容器中