SpringBoot
原理初探
自动配置:
pom.xml
- spring-boot-dependencies: 核心依赖在父工程中!
- 我们在写或者引入一些springboot依赖的时候,不需要指定版本,就因为有这些版本仓库.
启动器
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
-
启动器:说白了就是springboot的启动场景
-
比如spring-boot-starter-web,他就会帮我们自动导入web环境所有的依赖!
-
springboot会将所有的功能场景,都变成一个个的启动器
-
我们要使用什么功能只需要找对应的启动器
starter
主程序
@SpringBootApplication
public class SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityApplication.class, args);
}
}
注解:
@SpringBootConfiguration :springboot的配置
@Configuration: spring配置类
@Component: 说明这也是一个spring的组件
@EnableAutoConfiguration: 自动配置
@AutoConfigurationPackage :自动配置包
@Import(AutoConfigurationPackages.Registrar.class) 自动配置 自注册
@Import(AutoConfigurationImportSelector.class)
springboot所有的自动配置都是在启动的时候扫描并加载:spring.factories
所有的自动配置类都在这里,但是不一定生效,判断条件是否成立,只要导入了对应的satart,就有对应的容器,有了启动器,自动装配就会生效,配置成功
SpringApplication.run();
主要分为两部分,一部分是springApplication的实例化,而是run方法的执行;
- SpringApplication
- 推断应用 的类型是普通的项目还是web项目
- 查找并加载所有可用初始化器,设置到initializers属性中
- 找出所有的应用程序监听器,设置到listeners属性中
- 推断并设置main方法的定义类,找到运行的主类
// SpringApplication构造器
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
this.webApplicationType = WebApplicationType.deduceFromClasspath();
this.bootstrappers = new ArrayList<>(getSpringFactoriesInstances(Bootstrapper.class));
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
```总结:
1. springboot启动会加载大量的自动配置类
2. 我们看我们需要的功能有没有在springboot默认写好的自动配置类中;
3. 自动配置中配置的组件中只要有我们需要的,我们就不需要再手动配置了
4. 给容器中自动配置类添加组件的时候,会从properties类中获取某些属性.我们只需要在配置文件中指定这些属性的值即可;
xxxAutoConfiguration:自动配置类;给容器添加组件
xxxProperties:封装配置文件中相关的属性
## springBoot配置位置优先级
```text
1.file:./config/
2.file:./
3.classpath:/config/
4.classpath:/
静态资源默认的映射路径有
//WebProperties
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/" };