一、简单构建一个springboot项目
@SpringBootApplication public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }
只要启动上述代码,就能启动一个基本的springboot项目,springboot启动的核心就在于 @SpringBootApplication 注解以及 SpringApplication.run(SpringbootApplication.class, args);
下面也将围绕这两个方法进行讲解。
二、@SpringBootApplication 原理
@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 {
源码如上,可以看到@SpringBootApplication 是个符合注解,其中重点是
-
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
- @EnableAutoConfiguration
2.1 第一个注解@ComponentScan
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
扫码根路径下所有@Controller @Service @Respository @componet 并注入到spring容器中,然后排除TypeExcludeFilter和AutoConfigurationExcludeFilter中定义的bean。
2.2 第二个注解:@EnableAutoConfiguration (核心)
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import(AutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration {
查看源码可知,@EnableAutoConfiguration也是一个符合注解,其中
- @Import(AutoConfigurationImportSelector.class)
- @AutoConfigurationPackage
2.2.1 @Import(AutoConfigurationImportSelector.class)
@import注解用于将bean导入到spring容器中,具体哪些bean需要导入容器则查看AutoConfigurationImportSelector 源码,查看AutoConfigurationImportSelector 的
selectImports 方法,该方法加载META-INF/spring.factories下EnableAutoConfiguration的类(常用的JdbcTemplateAutoConfiguration等自动注解类)加载到容器中,如下图spring.factories
- @EnableAutoConfiguration