1.springboot启动
1.1创建一个maven项目
1.2.配置pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.itsource</groupId>
<artifactId>springboot_01</artifactId>
<version>1.0-SNAPSHOT</version>
<name>springboot_01</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.13.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
1.3.创建一个HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "你好啊,王哈哈!!!";
}
}
1.4.创建一个配置类ApplicationConfig
/* @Configuration
* @EnableAutoConfiguration//开启自动配置
* @ComponentScan
* 这三个注解相当于@SpringBootApplication
*/
@SpringBootApplication
public class ApplicatianConfig
{
public static void main( String[] args )
{
SpringApplication.run(ApplicatianConfig.class,args);
}
}
2.springboot运行原理
2.1.首先从==@SpringBootApplication这个注解讲起,@SpringBootApplication包含这三个注解 (@Configuration、@EnableAutoConfiguration//开启自动配==、@ComponentScan)
2.2.查看@SpringBootApplication源码再找到@EnableAutoConfiguration的源码,能够看到AutoConfigurationImportSelector
2.3.查看AutoConfigurationImportSelector源码,
而在AutoConfigurationImportSelector中有一个方法selectImports(),
2.4.点击getAutoConfigurationEntry跳转到这
2.5.点击getCandidateConfigurations
2.6.寻找到META-INF/spring.factories
2.7.spring.factories文件是一组一组的key=value的形式
总结:
@EnableAutoConfiguration注解通过@SpringBootApplication被间接的标记在了Spring Boot的启动类上。在SpringApplication.run(…)的内部就会执行selectImports()方法,找到所有JavaConfig自动配置类的全限定名对应的class,然后将所有自动配置类加载到Spring容器中。