简要说明
简单一点就是 : 扫描到spring.factories中的EnableAutoConfiguration,进行注入。比如RedisAutoConfiguration.class中的@bean注解,应该就明白,这里和spring中创建通过注解创建bean一样了。后面详细说明。 @Bean怎么注入ioc不明白可以去看一下spring ioc。
这里随便取一个spring.factories
那么现在问题就是spring是如何找到该类或者该注解,并且注入进容器的。
再简单说下。
就是在Spring ioc容器创建refresh()的时候,在执行beanFactoryPostProcessor链条的时候有类扫描到 springbootApplication主类上的注解@springBootApplication ,里的@EnableAutoConfiguration 里的@import(AutoConfIgurationImportSelector.class). AutoConfIgurationImportSelector类中会加载spring.factories中的EnableAutoConfiguration对应的类。后面会列出。将里面的bean统一转化为BeanDefinition等待后面初始化。
springboot启动流程
- 入口启动类
@EnableDiscoveryClient
@SpringBootApplication
public class SpringDemoApplication {
public static void main(String[] args) {
SpringApplication.run(UserCenterApplication.class, args);
}
}
springboot启动的入口,通过run进去就可以看到会初始化一个SpringApplication,然后执行run方法。
- 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 = deduceWebApplicationType();
//读取化加载器
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
//读取监听器
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
getSpringFactoriesInstances(XXXXX.class) 这个方法在springboot初始化经常会看到。从名字也可以看出,其实就是从META-INF/spring.factories通过反射加载该类型的类。
- SpringApplication.run具体执行过程 (这个是springApplication中的方法)
public ConfigurableApplicationContext run(String... args) {