SpringBoot源码
springboot总体过程
- 1.使用SPI技术动态加载META-INF/spring.factories配置文件中的类。
- 2.初始化入口main类。
- 3.初始化springboot容器(createApplicationContext处注册@Configuration和@Autowired等注解后置处理器到BeanFactory)。
- 4.获取BeanFactory后置处理器,执行postProcessBeanFactory方法。
- 5.调用finishBeanFactoryInitialization方法,实例化bean,然后缺少属性对象的,接着实例化属性对象,然后属性设置,实例化bean后执行bean后置处理器。
大体步骤
- new SpringApplication(primarySources);
- 执行run();方法
- 执行refresh();方法
new SpringApplication(primarySources)逻辑
- 第一步,判断web应用是reactive应用还是servlet应用。
- 第二步,使用SPI技术加载接口BootstrapRegistryInitializer.class、ApplicationContextInitializer.class、ApplicationListener.class接口对应的实现类。
- 第三步,初始化main类。
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
// 初始化资源加载器
this.resourceLoader = resourceLoader;
// 校验资源不为null
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
// 判断使用的容器类型
/**
* 有这个org.springframework.web.reactive.DispatcherHandler类,
* 没有这个org.springframework.web.servlet.DispatcherServlet类,
* 你那么采用reactive响应式编程,否则默认采用sevlet
*/
this.webApplicationType = WebApplicationType.deduceFromClasspath();
// 加载classpath下META-INF/spring.factories中配置的BootstrapRegistryInitializer对应的实现类
this.bootstrapRegistryInitializers = new ArrayList<>(
getSpringFactoriesInstances(BootstrapRegistryInitializer.class));
// 加载classpath下META-INF/spring.factories中配置的ApplicationContextInitializer对应的实现类
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
// 加载classpath下META-INF/spring.factories中配置的ApplicationListener对应的实现类
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
// 初始化入口main类
this.mainApplicationClass = deduceMainApplicationClass();
}
- SPI技术加载/META-INF/spring.factories文件下的接口对应的实现类:
https://www.cnblogs.com/sunpeiyu/articles/17398612.html
SpringApplication对象的run方法逻辑
- 第1步:configureHeadlessProperty方法,设置系统变量java.awt.headless
- 第2步:getRunListeners方法,加载启动SpringApplicationRunListener监听器
- 第3步:prepareEnvironment方法,创建配置environment对象
- 第4步:printBanner方法,打印banner
- 第5步:createApplicationContext方法,根据webApplicationType配置创建上下文context,注册@Configuration、@Autowired注解后置处理器到beanDefinitionMap中。
- 第6步:prepareContext方法,初始化循环依赖为false、BeanDefinition重写覆盖为false、初始化懒加载后置处理器
- 第7步:refreshContext方法,刷新容器(refreshContext -> refresh)
- 第8步:监听器发布ApplicationStartedEvent事件和ApplicationReadyEvent事件
/**
* 初始化SpringBoot
* 创建且配置ApplicationContext
*/
public ConfigurableApplicationContext run(String... args) {
long startTime = System.nanoTime();
// 初始化SpringBoot的第一个容器DefaultBootstrapContext,将
DefaultBootstrapContext bootstrapContext = createBootstrapContext();
ConfigurableApplicationContext context = null;
// 设置系统变量java.awt.headless
configureHeadlessProperty();
// 加载SpringApplicationRunListener监听器
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting(bootstrapContext, this.mainApplicationClass);
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 创建配置environment
ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
// spring.beaninfo.ignore字段,忽略配置bean信息,
configureIgnoreBeanInfo(environment);
// 打印banner,可以自定义
Banner printedBanner = printBanner(environment);
// 反射构造AnnotationConfigServletWebServerApplicationContext (ApplicationContext)
// 加载BeanFactory的后置处理器,
// 如ConfigurationClassPostProcessor可以加载@Configuration注解后置处理器
// 将注解后置处理器解析放到BeanDefinitionMap中
// ApplicationContext -> BeanFactory -> BeanDefinitionMap
context = createApplicationContext();
context.setApplicationStartup(this.applicationStartup);
// 配置的environment设置到context上下文
// 初始化循环依赖配置为false
// BeanDefinition重写覆盖为false
// 初始化懒加载后置处理器初始化懒加载后置处理器
prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
// 执行bean的后置处理器,实例化bean
refreshContext(context);
afterRefresh(context, applicationArguments);
Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime);
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), timeTakenToStartup);
}
listeners.started(context, timeTakenToStartup);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, listeners);
throw new IllegalStateException(ex);
}
try {
Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime);
listeners.ready(context, timeTakenToReady);
}
catch (Throwable ex) {
handleRunFailure(context, ex, null);
throw new IllegalStateException(ex);
}
return context;
}
createApplicationContext方法,加载BeanFactory后置处理器:
- createApplicationContext方法
protected ConfigurableApplicationContext createApplicationContext() {
return this.applicationContextFactory.create(this.webApplicationType);
}
ApplicationContextFactory DEFAULT = (webApplicationType) -> {
try {
switch (webApplicationType) {
case SERVLET:
return new AnnotationConfigServletWebServerApplicationContext();
case REACTIVE:
return new AnnotationConfigReactiveWebServerApplicationContext();
default:
return new AnnotationConfigApplicationContext();
}
}
catch (Exception ex) {
throw new IllegalStateException("Unable create a default ApplicationContext instance, "
+ "you may need a custom ApplicationContextFactory", ex);
}
};
public AnnotationConfigServletWebServerApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
- AnnotatedBeanDefinitionReader构造器
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
this(registry, getOrCreateEnvironment(registry));
}
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
- AnnotationConfigUtils.registerAnnotationConfigProcessors方法
将BeanFactory后置处理器封装成BeanDefinition,调用registerPostProcessor方法注册这些封装好的BeanDefinition。
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
registerAnnotationConfigProcessors(registry, null);
}
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
// 加载ConfigurationClassPostProcessor.class后置处理器
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// 加载AutowiredAnnotationBeanPostProcessor.class后置处理器
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// 加载CommonAnnotationBeanPostProcessor.class后置处理器
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// 加载PersistenceAnnotationBeanPostProcessor.class后置处理器
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// 加载EventListenerMethodProcessor.class后置处理器
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}
// 加载DefaultEventListenerFactory.class后置处理器
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
- registerPostProcessor方法,注册后置处理器
// 注册后置处理器
private static BeanDefinitionHolder registerPostProcessor(
BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
// 注册BeanDefinition到BeanDefinitionMap中
registry.registerBeanDefinition(beanName, definition);
return new BeanDefinitionHolder(definition, beanName);
}
- registerBeanDefinition方法,注册BeanDefinition,实际就是存到beanDefinitionMap里面
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
Assert.hasText(beanName, "Bean name must not be empty");
Assert.notNull(beanDefinition, "BeanDefinition must not be null");
// 判断BeanDeifnition是否为AbstractBeanDefinition类型
if (beanDefinition instanceof AbstractBeanDefinition) {
try {
((AbstractBeanDefinition)beanDefinition).validate();
} catch (BeanDefinitionValidationException var8) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Validation of bean definition failed", var8);
}
}
// 判断beanName的BeanDefinition是否存在
BeanDefinition existingDefinition = (BeanDefinition)this.beanDefinitionMap.get(beanName);
if (existingDefinition != null) {
if (!this.isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
}
if (existingDefinition.getRole() < beanDefinition.getRole()) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Overriding user-defined bean definition for bean '" + beanName + "' with a framework-generated bean definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
}
} else if (!beanDefinition.equals(existingDefinition)) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Overriding bean definition for bean '" + beanName + "' with a different definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
}
} else if (this.logger.isTraceEnabled()) {
this.logger.trace("Overriding bean definition for bean '" + beanName + "' with an equivalent definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
}
this.beanDefinitionMap.put(beanName, beanDefinition);
} else {
if (this.hasBeanCreationStarted()) {
synchronized(this.beanDefinitionMap) {
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
this.removeManualSingletonName(beanName);
}
} else {
// BeanDefinition存放到beanDefinitionMap
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
this.removeManualSingletonName(beanName);
}
this.frozenBeanDefinitionNames = null;
}
if (existingDefinition == null && !this.containsSingleton(beanName)) {
if (this.isConfigurationFrozen()) {
this.clearByTypeCache();
}
} else {
this.resetBeanDefinition(beanName);
}
}
prepareContext 方法, 加载启动类并且初始化循环依赖为false、BeanDefinition重写覆盖为false、初始化懒加载后置处理器
private void prepareContext(DefaultBootstrapContext bootstrapContext, ConfigurableApplicationContext context,
ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments, Banner printedBanner) {
context.setEnvironment(environment);
postProcessApplicationContext(context);
applyInitializers(context);
listeners.contextPrepared(context);
bootstrapContext.close(context);
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
// Add boot specific singleton beans
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof AbstractAutowireCapableBeanFactory) {
((AbstractAutowireCapableBeanFactory) beanFactory).setAllowCircularReferences(this.allowCircularReferences);
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory) beanFactory)
.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
}
if (this.lazyInitialization) {
context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
}
// Load the sources
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
// 加载启动类
load(context, sources.toArray(new Object[0]));
listeners.contextLoaded(context);
}
refresh方法
- 第1步:obtainFreshBeanFactory方法,获取DefaultListableBeanFactory工厂对象
- 第2步:prepareBeanFactory方法,设置工厂对象的属性
- 第3步:postProcessBeanFactory方法,钩子方法,预留给子类实现,在工厂对象准备刷新容器前做一些处理
- 第4步:invokeBeanFactoryPostProcessors方法,获取BeanFactoryPostProcessor执行postProcessBeanFactory方法
- 第5步:registerBeanPostProcessors方法,获取所有的BeanPostProcessor并注入到beanFactory
- 第6步:finishBeanFactoryInitialization方法(判断bd是否是FactoryBean,如果是则调用FactoryBean的方法创建bean,如果不是则调用getBean方法创建bean,主要流程就先从缓存中获取bean,获取不到就从头开始创建bean,并经过bean的实例化、属性赋值、初始化的生命周期,中间调用Aware类的方法和上面注册的BeanPostProcessor的前后置方法,完成IOC创建)
getBean的实现,可以参考:
SpringBoot IOC源码
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// 创建并设置了Environment对象
prepareRefresh();
// 获取BeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 填充beanFactory的属性
prepareBeanFactory(beanFactory);
try {
// AbstractApplicationContext中该方法是个空方法,留给子类进行扩展
// 子类可以实现BeanPostProcessor接口,spring里会进行回调
// 在所有beanDefinition加载完成之后,bean实例化之前执行
// 一般是为了修改BeanDefinition或者对BeanFactory做其他配置
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// 将BeanFactoryPostProcessor注册到BeanFactory上面
// 加载注解@SpringBootApplication、还递归加载其父类@EnableAutoConfiguration、@Import
invokeBeanFactoryPostProcessors(beanFactory);
// 获取所有的BeanPostProcessor并注入到beanFactory
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// 国际化
initMessageSource();
// 初始化事件广播器。如果自定义了广播器,用自定义的
initApplicationEventMulticaster();
// 空方法,留给子类来初始化其他bean
onRefresh();
// 在所有注册的bean中查找listener bean,注册到消息广播器中
registerListeners();
// 实例化所有剩余的(非懒加载)单例Bean
finishBeanFactoryInitialization(beanFactory);
// 清除上下文资源缓存(如扫描中的ASM元数据)
// 初始化上下文的生命周期处理器,并刷新(找出Spring容器中实现了Lifecycle接口的bean并执行start()方法)
// 发布ContextRefreshedEvent事件告知对应的ApplicationListener进行响应的操作
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
contextRefresh.end();
}
}
}
invokeBeanFactoryPostProcessors方法,将BeanFactoryPostProcessor注册到BeanFactory上面。
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
- PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors方法
- ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry方法
- ConfigurationClassPostProcessor.processConfigBeanDefinitions方法
将bean解析放到beanDefinitionMap中。
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
String[] candidateNames = registry.getBeanDefinitionNames();
// for循环代码干了一件事就是
// 将@Configuration注解beanFactory后置处理器(ConfigurationClassPostProcessor)放入configCandidates
for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}
// Return immediately if no @Configuration classes were found
if (configCandidates.isEmpty()) {
return;
}
// Sort by previously determined @Order value, if applicable
// 将beanFactory后置处理器根据实现order接口排序
configCandidates.sort((bd1, bd2) -> {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return Integer.compare(i1, i2);
});
。。。
// 解析每一个@Configuration类
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
do {
StartupStep processConfig = this.applicationStartup.start("spring.context.config-classes.parse");
// 递归处理超类,如META-INF下@EnableAutoConfiguration、@Import
parser.parse(candidates);
parser.validate();
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);
// Read the model and create bean definitions based on its content
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
// 加载配置类
this.reader.loadBeanDefinitions(configClasses);
alreadyParsed.addAll(configClasses);
processConfig.tag("classCount", () -> String.valueOf(configClasses.size())).end();
candidates.clear();
if (registry.getBeanDefinitionCount() > candidateNames.length) {
String[] newCandidateNames = registry.getBeanDefinitionNames();
Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
Set<String> alreadyParsedClasses = new HashSet<>();
for (ConfigurationClass configurationClass : alreadyParsed) {
alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
}
for (String candidateName : newCandidateNames) {
if (!oldCandidateNames.contains(candidateName)) {
BeanDefinition bd = registry.getBeanDefinition(candidateName);
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());
// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
}
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
// Clear cache in externally provided MetadataReaderFactory; this is a no-op
// for a shared cache since it'll be cleared by the ApplicationContext.
((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
}
}
核心实现:
- 3.1 parser.parse方法,扫描@ComponentScan路径下的所有的BeanDefinition,以及@Import的BeanDefinition,使用递归方法扫描,最终放入this.configurationClasses。
- 3.2 转化this.configurationClasses为configClasses对象(Set集合)
- 3.3 this.reader.loadBeanDefinitions(configClasses)方法,注册beanDefinition到beanDefinitionMap。
具体逻辑:
SpringBoot自动装配源码
SpringBoot IOC
由于本篇内容太多,IOC就放到了另一篇
SpringBoot IOC源码
@SpringBootApplication注解
源码思路
- 第1步:@SpringBootApplication注解 -> @EnableAutoConfiguration注解
- 第2步:@EnableAutoConfiguration注解 -> @Import(AutoConfigurationImportSelector.class)注解
- 第3步:执行类AutoConfigurationImportSelector的selectImports方法
- 第4步:selectImports方法委派给getAutoConfigurationEntry方法
- 第5步:getAutoConfigurationEntry方法委派给getCandidateConfigurations方法
- 第6步:getCandidateConfigurations -> 通过SpringFactoriesLoader.loadFactoryNames,从META-INF/spring.factories读取EnableAutoConfiguration的类为key,value为需要自动装配的xxxConfiguration配置类的数组,通过SpringFactoriesLoader机制创建对应的bean,注入到容器中,完成了自动装配。