微服务阶段
原理初探
pom.xml
- spring-boot-dependencies:核心依赖在父工程中!
- 我们在写或者引入一些springboot依赖的时候,不需要指定版本,就因为有这些版本仓库
启动器
-
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> 进入父项目 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.1.9.RELEASE</version> <relativePath>../../spring-boot-dependencies</relativePath> </parent>
- 启动器:说白了就是Springboot的启动场景
- 比如spring-boot-starter-web,他就会帮我们自动导入web环境所有的依赖!
- springboot会将所有场景都变成一个个启动器
- 我们要是用什么功能,就只需要找到对应的启动器就可以了 ‘starter’
主程序
// @SpringBootApplication 标注这个类是一个springboot的应用
@SpringBootApplication
public class HelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloworldApplication.class, args);
}
}
- 注解
-
@SpringBootConfiguration : springboot的配置 @Configuration: spring 配置类 @Component: 说明这也是一个spring的组件 @EnableAutoConfiguration : 自动配置 @AutoConfigurationPackage: 自动配置包 @Import({AutoConfiguration.Registrar.class}): 自动配置‘包注册’ @Import({AutoConfigurationImportSelector.class}): 自动导入选择 // 获取所有配置 List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes)
-
获取候选的配置
-
META-INF/spring.factories: 自动配置的核心文件
结论:springboot中所有的自动配置都是在启动的时候扫描并加载,但是不一定生效,但是要判断条件是否成立,只要导入了对应的start,就有了对应的启动器了,有了启动器,我们的自动装配就会生效,然后启动成功!!
-
- springboot在启动的时候,在类路径下 /META-INF/spring.factories 获取指定的值
- 将这些自动配置的类导入容器,自动配置就会生效,帮我们进行自动配置
- 以前我们需要自动配置的东西,现在springboot帮我们做了!
- 整合javaEE,解决方案和自动配置的东西都在spring-boot-autoconfigure:2.2.4.RELEASE.jar中
- 他会把所有需要导入的组件,以类名的方式返回,这些组件就会被添加到容器中
- 容器中也会存在非常多的XXXAutoConfiguration文件(@),就是这些文件给容器中导入了这个场景需要的所有组件;并自动配置,@Configuration,JavaConfig!
- 有了自动配置类,免去了我们手动编写配置文件的工作
关于spring boot,谈谈你的理解:
- 自动装配
- run()
-
SpringApplication.run分析
分析该方法主要分两部分,一部分是SpringApplication的实例化,二是run方法的执行;
SpringApplication
这个类主要做了以下四件事情- 推断应用的类型是普通的项目还是Web项目
- 查找并加载所有可用初始化器 , 设置到initializers属性中
- 找出所有的应用程序监听器,设置到listeners属性中
- 推断并设置main方法的定义类,找到运行的主类
查看构造器public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) { this.sources = new LinkedHashSet(); this.bannerMode = Mode.CONSOLE; this.logStartupInfo = true; this.addCommandLineProperties = true; this.addConversionService = true; this.headless = true; this.registerShutdownHook = true; this.additionalProfiles = new HashSet(); this.isCustomEnvironment = false; this.resourceLoader = resourceLoader; Assert.notNull(primarySources, "PrimarySources must not be null"); this.primarySources = new LinkedHashSet(Arrays.asList(primarySources)); this.webApplicationType = WebApplicationType.deduceFromClasspath(); this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class)); this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class)); this.mainApplicationClass = this.deduceMainApplicationClass(); }
run方法
-
全面接管SpringMVC的配置!!实操!!