springboot我们都用过,他帮我们省去了繁杂的配置过程,让我们开箱即用,加快了我们的开发效率.
那么springboot究竟是如何实现的呢?在任何一个springboot项目上,我们都会在启动类上加上@SpringBootApplication注解,并在main方法上写上了SpringBootApplication.run();项目就运行了.
点开@SpringBootApplication注解会发现上面有7个注解
- @Target
- @Retention
- @Doucument
- @Inherit
- @SpringBootConfiguration
- @EnnableAutoConfiguration
- @ComponentScan
前四个是元注解就不再多说了 ,
@SpringBootConfiguration也就是包含了@Configuration注解,即将当前类标位配置类,这个在spring的时代就有了,通过@Configuration和@Bean注解将javabean放入spring容器
@EnableAutoConfiguration注解就是开始了自动配置
在我们引入的jar包依赖中,有个META-INFO文件夹,内部有spring.fatories文件,
文件内部有一个字段是org.springframework.boot.autoconfigure.EnableAutoConfiguration
它内部借用AutoConfigurationImportSelector的selectImports方法,最终调用SpringFactoriesLoader.loadFactoryNames()方法加载该字段的所有类名字,通过反射创建对象并注入spring容器
@ComponentScan注解就是扫描标注类所在包和所有子包中的类.
如果一个子包中的类标注了@Component,@Service,@Controller,@Repository注解的话,就会将该类装载进spring容器.