原理初探
自动装配:
pom.xml
- spring-boot-dependencies:核心功能在父工程中
- 我们在写入或引入一些SpringBoot依赖的时候,不需要指定版本,是因为有这些版本仓库
启动器
-
<!--启动器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>
-
启动器说白了就是springboot的启动场景;
-
比如spring-boot-starter-web,他就会帮我们自动导入web环境的所有依赖!
-
springboot会将所有的功能场景,都变成一个个的启动器
-
我们要使用什么功能,就只需要找到对应的启动器就可以了
starter
主程序
//@SpringBootApplication:标注这个类是一个springboot的应用,启动类下的所有资源被导入
@SpringBootApplication
public class SpringbootDemo02Application {
//将springboot应用启动
public static void main(String[] args) {
SpringApplication.run(SpringbootDemo02Application.class, args);
}
}
-
注解
-
@SpringBootConfiguration : springboot的配置 @Configuration:spring配置类 @Component:说明这也是spring的一个组件 @EnableAutoConfiguration:自动配置 @AutoConfigurationPackage:自动配置包 @Import({Registrar.class}):自动配置'包注册' @Import({AutoConfigurationImportSelector.class}):自动配置导入选择 //获取所有的配置 List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
获取候选的配置(getCandidateConfigurations)
-
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); return configurations; }
META-INF/spring.factories:自动配置的核心文件
Properties properties = PropertiesLoaderUtils.loadProperties(resource); 所有资源加载到配置类中!
-
-
核心注解:@ConditionalOnXXX:如果这里面的条件都满足了,才会生效。
结论
springboot所有自动配置都是在启动的时候扫描并加载;spring.factories
所有的自动配置类都在这里面,但是不一定生效,要判断条件是否成立,只要导入了对应的start,就有了对应的启动器了,有了启动器,我们自动装配就能生效,然后就配置成功了!
步骤
1. springboot在启动的时候,从类路径下/METE-INF/spring.factories获取指定的值。
2. 将这些自动配置的类导入容器,自动配置类就会生效,帮我进行自动配置。
3. 以前我们需要自动配置的东西,现在springboot帮我们做了!
4. 整个JavaEE,解决方案和自动配置的东西都在`spring-boot-autoconfigure`这个包下。
5. 它会把所有需要导入的组件,以类名的方式返回,这些组件就会被添加到容器。
6. 容器中也会存在非常多的xxxAutoConfiguration的文件(@Bean),就是这些类给容器中导入了这个场景需要的所有组件;并自动配置,@Configuration,JavaConfig!
7. 有了自动配置类,免去了我们手动编写配置文件的工作!
JavaConfig @Configuration @Bean
Docker:进程
面试
关于springboot,谈谈你的理解:
- 自动装配
- run();方法
- 判断是普通项目还是web项目
- 会去推断当前的主类
- 会存在一些(全局)监听器:会去获取上下文,处理我们的一些bean
全面接管SpringMVC的配置!(实操!)