之前的文章中进行过springboot的一些使用,再说一说一些加强的内容.
SpringBoot启动原理说明
我们都知道springboot十分强大,可以实现零配置/少配置运行,以及开箱即用的特性,那么他是怎么做到的呢?
pom.xml
当我们创建一个springboot项目,并只在创建时导入spring web依赖时可以看到pom.xml中有什么配置:
4.0.0
com.jt
springboot_demo1
0.0.1-SNAPSHOT
springboot_demo1
入门案例
org.springframework.boot
spring-boot-starter-parent
2.3.3.RELEASE
1.8
true
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
pom.xml文件内标签的含义在上述代码中有所注释.
开箱即用
开箱即用:指项目中只需要注入少量的jar包及配置,就可拥有其功能.
就是上述的pom.xml中的spring-starter启动项拥有开箱即用的能力.
上图是开箱即用特性的一个梳理,接下来说一下:
首先启动类会执行
SpringApplication.run(SpringbootDemo01Application.class, args);
run方法会加载@SpringBootApplication注解:
- 有元注解(修饰注解的注解)
@Target(ElementType.TYPE)//注解对类有效
@Retention(RetentionPolicy.RUNTIME)//在运行期有效
@Documented//动态生成文档信息
@Inherited//可以被继承
2.加载对象,但要排除的过滤器
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
3.springboot配置类
@SpringBootConfiguration又由@Configuration配置类以及元注解修饰
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {}
意味着主启动类本身就是一个超大的配置文件,可以去加载其他@Configuration注解描述的类,当启动类加载时,其他类都会加载.
4.完成开箱即用配置
@EnableAutoConfiguration由元注解以及@AutoConfigurationPackage和@Import(AutoConfigurationImportSelector.class)修饰
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {}
@AutoConfigurationPackage--自动按照包扫描的方式实例化对象,之后所有的配置都需要在启动类所在包以及子孙包中进行定义.
@Import(AutoConfigurationImportSelector.class)--当程序启动时,根据SpringBoot中的Seletor选择器,去检查pom.xml文件中是否添加了启动项的包.