环境:JDK1.8、MAVEN 3.6.1、eclipse、Spring Boot版本1.2.4.RELEASE
1.SpringBoot的启动类SpringApplication
//注解配置程序上下文的类全名称:默认的上下文类
private static final String DEFAULT_CONTEXT_CLASS = "org.springframework.context."
+ "annotation.AnnotationConfigApplicationContext";
//注解配置启用web程序上下文的类全名称:默认的web上下文类
public static final String DEFAULT_WEB_CONTEXT_CLASS = "org.springframework."
+ "boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext";
//配置web程序上下文类:web环境类
private static final String[] WEB_ENVIRONMENT_CLASSES = { "javax.servlet.Servlet",
"org.springframework.web.context.ConfigurableWebApplicationContext" };
.....其中定义了基本的SpringBoot的启动图标,还有日志的配置,以及当前的application.properties文件中的属性存放的属性
2.查看SpringApplication的run方法
1.发现调用本类中的run(new Object[] { source }, args);
实际调用new SpringApplication(sources).run(args)
;创建SpringApplication对象,并将当前的传递的Application.class变成sources传进来,开始初始化数据:initialize(sources);
2.在initialize方法中。
- 通过
getSpringFactoriesInstances初始化SpringBoot所以来的类
,和实例。通SpringFactoriesLoader.loadFactoryNames()来读取META-INF/spring.factories中
定义的内容并加载添加到LinkedHashSet
中,然后通过ClassUtils.forName(name, classLoader);的方式创建类
,通过构造函数实例化定义的类,然后把当前创建的实例添加到ArrayList
中,最后排序AnnotationAwareOrderComparator.sort();实例化的类
- 通过
getSpringFactoriesInstances初始化监听
,和所有的监听 - 最后获取入口类的Class
3.查看当前的run方法
- 1.配置当前的
系统属性和系统的变量
- 2.加载程序所需要的
监听
- 3.创建和配置
environment
- 4.创建
ConfigurableApplicationContext,通过createApplicationContext()
创建,会自动判断当前的程序是否式web程序,最后创建该配置实例 - 5.调用
refresh()
进行刷新当前的所有配置 - 6.最后启动
3.查看@SpringBootApplication注解
当前的
@SpringBootApplication
注解的内容:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {
/**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
Class<?>[] exclude() default {};
}
1.@Configuration:其实就是@Component
2.@EnableAutoConfiguration:开启自动配置
3.@ComponentScan:组件扫描用于扫描@Component等
4.查看@EnableAutoConfiguration注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({ EnableAutoConfigurationImportSelector.class,
AutoConfigurationPackages.Registrar.class })
public @interface EnableAutoConfiguration {
/**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
Class<?>[] exclude() default {};
}
发现:@Import({ EnableAutoConfigurationImportSelector.class,
AutoConfigurationPackages.Registrar.class }),说明当前的@EnableAutoConfiguration注解其实就是通过这两个类实现的
5.总结
1.当前的类通过run方法加载当前类
2.通过注解的解析器解析,并通过创建AutoConfigurationPackages
或者EnableAutoConfigurationImportSelector
自动加载并配置
3.通过扫描和读取当前的META-INF/spring.factories
文件进行SpringBoot依赖的初始化
4.spring.factories
定义了一系列的SpringBoot所需要的类