SpringBoot 入门学习

SpringBoot 入门学习

1、创建spring boot项目

网页创建

idea创建

image

2、原理初探

pom.xml

  • spring-boot-dependencies:核心依赖在父工程中

  • 我对门在引入一些spring boot依赖的时候,可以不需要指明版本,就是因为有这个版本仓库

启动器

  • <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter</artifactId>
    </dependency>
    
  • 启动器就是spring boot的启动场景

  • 比如spring-boot-starter-web,它就会帮我们导入所有web环境所需的依赖,还内嵌了tomcat容器

  • spring boot将所有功能场景,都变成一个个的启动器

  • 我们要使用什么功能,只需要找到对应的启动器就行了

主程序

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

// SpringBootApplication:标注这个类是一个springboot的应用:启动类下的所有资源被导入
@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
        // 启动spring boot应用
		SpringApplication.run(DemoApplication.class, args);
	}

}
  • 注解

    • @SpringBootConfiguration:spring boot的配置
      	@Configuration:spring配置类
          @Component:说明这也是一个spring的组件
      
      @EnableAutoConfiguration:自动配置导入包
          @AutoConfigurationPackage:自动配置包
          	@Import({Registrar.class}):自动配置’包注册‘
          @Import({AutoConfigurationImportSelector.class}):自动配置导入选择
      
      @ComponentScan:扫描当前启动类同级的包
          
      //AutoConfigurationImportSelector类中
      //获取所有的配置
      List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
      

      获取候选的配置

      protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
          List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.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;
      }
      

image

META-INF/spring.factories:自动配置的核心文件,所有自动配置类都在这里

image

// 所有的资源加载到配置类中
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
  • 结论:spring boot所有自动配置都是在启动的时候扫描并加载,spring.factories所有的自动配置类都在这里面,但是不一定生效,要判断条件是否成立@ConditionalOnxxx注解,只要导入了对应的启动器start,条件成立了,自动装配就会生效,即配置成功。
posted @ 2021-05-08 16:01  金盛年华  阅读(63)  评论(0)    收藏  举报