SpringBoot原理初探
约定由于配置
使用spring、springmvc、mybatis框架会发现你需要些很多的xml文件,配置起来很繁琐,开发速度会降低。springboot框架基于spring框架的基础上进行封装,将很多的配置封装在属性。只需要在yml文件中配置就行了,如果有自定义的配置也可以自定义配置,简化了我们的操作。springboot还解决了依赖冲突的问题
开箱即用
只需要声明,直接拿来用就行
<!--引入Web starter 启动器 常见的web场景-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
注解
@SpringBootApplication 注解
SpringBootApplication这个注解里面提供了三个注解
1.@ComponentScan 扫描我们写的一些组件, 扫描的是 启动类所在的包下的所有组件
2.@EnableAutoConfiguration 这个注解是springboot的核心注解,开启自动配置和自动装配 它所加的组件 就是我们在 pom中 申明 的组件 以及 springBoot默认提供给我用的组件啊 将组件实例化,交由IOC容器去管理
@Import注解是核心中的核心
springboot会帮我们去过滤和筛选,不是所有的配置都会用上
3.@SpringBootConfiguration 是一个springboot的配置类,能被组件扫描
再往下
程序
SpringApplication
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.lazyInitialization = false;
this.resourceLoader = resourceLoader;//初始化资源加载器
Assert.notNull(primarySources, "PrimarySources must not be null");//资源加载类不能为空
this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));//初始化资源加载类集合并去重
this.webApplicationType = WebApplicationType.deduceFromClasspath();//判断程序是否Web应用程序
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));//设置初始化器
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));//设置监听器
this.mainApplicationClass = this.deduceMainApplicationClass();//推断出主应用入口类
}
properties
所有的配置在底层都对应了一个类的属性值
@ConfigurationProperties(
prefix = "spring.resources",
ignoreUnknownFields = false
)
public class ResourceProperties {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
private String[] staticLocations;
private boolean addMappings;
private final ResourceProperties.Chain chain;
private final ResourceProperties.Cache cache;
public ResourceProperties() {
this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
this.addMappings = true;
this.chain = new ResourceProperties.Chain();
this.cache = new ResourceProperties.Cache();
}
public String[] getStaticLocations() {
return this.staticLocations;
}
public void setStaticLocations(String[] staticLocations) {
this.staticLocations = this.appendSlashIfNecessary(staticLocations);
}
private String[] appendSlashIfNecessary(String[] staticLocations) {
String[] normalized = new String[staticLocations.length];
for(int i = 0; i < staticLocations.length; ++i) {
String location = staticLocations[i];
normalized[i] = location.endsWith("/") ? location : location + "/";
}
return normalized;
}