本文將通過閱讀AnnotationConfigApplicationContext源碼,分析Spring啟動(dòng)流程。
創(chuàng)建AnnotationConfigApplicationContext
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(XxConfig.class);
applicationContext.register(YyConfig.class);
applicationContext.refresh();
XxService xxService = applicationContext.getBean(XxService.class);
核心的啟動(dòng)邏輯都在refresh方法中。
構(gòu)造方法
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
AnnotatedBeanDefinitionReader類
定義了多個(gè)register方法,用于向Spring容器注冊(cè)BeanDefinition。
在創(chuàng)建AnnotatedBeanDefinitionReader時(shí),會(huì)向容器注冊(cè)幾個(gè)注解驅(qū)動(dòng)處理器:
- org.springframework.context.annotation.internalConfigurationAnnotationProcessor: ConfigurationClassPostProcessor
- BeanFactoryPostProcessor實(shí)現(xiàn),用于解析@Configuration類。
- 按優(yōu)先級(jí)排序,因?yàn)樵贎Configuration類中聲明的任何@Bean方法都必須在任何其他BeanFactoryPostProcessor執(zhí)行之前注冊(cè)其對(duì)應(yīng)的BeanDefinition。
- org.springframework.context.annotation.internalAutowiredAnnotationProcessor: AutowiredAnnotationBeanPostProcessor
- BeanPostProcessor實(shí)現(xiàn)類。
- @Autowired支持處理器。
- org.springframework.context.annotation.internalCommonAnnotationProcessor: CommonAnnotationBeanPostProcessor
- BeanPostProcessor實(shí)現(xiàn)類。
- 支持Resource、PostConstruct、PreDestroy等注解。
- org.springframework.context.event.internalEventListenerProcessor: EventListenerMethodProcessor
- org.springframework.context.event.internalEventListenerFactory: DefaultEventListenerFactory
ClassPathBeanDefinitionScanner類
BeanDefinition掃描器,在類路徑上檢測(cè)Bean,并將其注冊(cè)到Spring容器中。掃描的類是通過類型過濾器檢測(cè)到的。
refresh方法
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
} catch (BeansException 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();
}
}
}
prepareRefresh方法
Prepare this context for refreshing, setting its startup date and active flag as well as performing any initialization of property sources.
protected void prepareRefresh() {
// Switch to active.
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
// Initialize any placeholder property sources in the context environment.
// Replace any stub property sources with actual instances.
// web相關(guān)的ApplicationContext有實(shí)現(xiàn)
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
} else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
obtainFreshBeanFactory方法
Tell the subclass to refresh the internal bean factory.
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
由于AnnotationConfigApplicationContext繼承了GenericApplicationContext類,所以此處獲取到的是DefaultListableBeanFactory對(duì)象。
prepareBeanFactory方法
配置BeanFactory的標(biāo)準(zhǔn)上下文,例如上下文的ClassLoader和后置處理器。
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
// Standard implementation of the BeanExpressionResolver interface,
// parsing and evaluating Spring EL using Spring's expression module.
beanFactory.setBeanExpressionResolver(
new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
// 支持EnvironmentAware, MessageSourceAware, ApplicationContextAware等
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// ApplicationListenerDetector處理器自動(dòng)將ApplicationListener類型Bean添加容器
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// 注冊(cè)env bean
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory
.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
postProcessBeanFactory方法
Modify the application context's internal bean factory after its standard initialization. All bean definitions will have been loaded, but no beans will have been instantiated yet. This allows for registering special BeanPostProcessors etc in certain ApplicationContext implementations.
在標(biāo)準(zhǔn)初始化之后修改ApplicationContext的內(nèi)部bean工廠。所有的BeanDefinition都將被加載,但還沒有任何Bean被實(shí)例化。這允許在某些ApplicationContext實(shí)現(xiàn)中注冊(cè)特殊的BeanPostProcessors等。
invokeBeanFactoryPostProcessors方法
實(shí)例化并調(diào)用注冊(cè)的所有BeanFactoryPostProcessor,如果指定順序則按照順序調(diào)用,必須在單例實(shí)例化之前調(diào)用。
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 調(diào)用BeanFactoryPostProcessors
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 (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
調(diào)用BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor。
registerBeanPostProcessors方法
實(shí)例化并注冊(cè)所有BeanPostProcessor,如果指定順序則按照順序注冊(cè),必須在應(yīng)用Bean實(shí)例化之前調(diào)用。
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
把BeanPostProcessor實(shí)例添加到beanPostProcessors中:
- 從容器獲取所有的BeanPostProcessor Bean
- 按照以下順序注冊(cè):實(shí)現(xiàn)了PriorityOrdered接口、實(shí)現(xiàn)了Ordered接口、普通BeanPostProcessor、實(shí)現(xiàn)MergedBeanDefinitionPostProcessor接口
private static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
initMessageSource方法
國(guó)際化。
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
} else {
// Use empty MessageSource to be able to accept getMessage calls.
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
}
}
initApplicationEventMulticaster方法
初始化ApplicationEventMultimaster,如果Context中未定義,則使用SimpleApplicationEventMultimaster。
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster = beanFactory.getBean(
APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
} else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(
APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
}
}
onRefresh方法
可以重寫的模板方法,以添加指定的刷新邏輯。在初始化特殊Bean時(shí)調(diào)用,在實(shí)例化單例之前調(diào)用。
默認(rèn)什么都不做。
SpringBoot中的ServletWebServerApplicationContext實(shí)現(xiàn)類在這個(gè)階段創(chuàng)建WebServer。
registerListeners方法
添加實(shí)現(xiàn)ApplicationListener的Bean作為偵聽器。不會(huì)影響其他偵聽器,這些偵聽器可以在不使用Bean的情況下添加。
finishBeanFactoryInitialization方法
完成Bean工廠的初始化,初始化所有剩余的單例Bean。文章來源:http://www.zghlxwxcb.cn/news/detail-500951.html
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}
finishRefresh方法
完成刷新工作,調(diào)用LifecycleProcessor的onRefresh()方法并發(fā)布ContextRefreshedEvent事件。文章來源地址http://www.zghlxwxcb.cn/news/detail-500951.html
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
// Initialize lifecycle processor for this context.
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
啟動(dòng)流程
- 創(chuàng)建AnnotationConfigApplicationContext對(duì)象
- 創(chuàng)建AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner
- 向容器注冊(cè)幾個(gè)注解驅(qū)動(dòng)處理器:ConfigurationClassPostProcessor, AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor等
- 調(diào)用applicationContext.register(XxConfig.class)注冊(cè)配置類
- 調(diào)用refresh()方法:
- prepareRefresh方法準(zhǔn)備工作:初始化PropertySources、validateRequiredProperties等
- Refresh the internal beanFactory
- 配置BeanFactory的標(biāo)準(zhǔn)上下文,例如上下文的ClassLoader和后置處理器
- 實(shí)例化并調(diào)用注冊(cè)的所有BeanFactoryPostProcessor,如果指定順序則按照順序調(diào)用,必須在單例實(shí)例化之前調(diào)用
- 實(shí)例化并注冊(cè)所有BeanPostProcessor,如果指定順序則按照順序注冊(cè),必須在應(yīng)用Bean實(shí)例化之前調(diào)用
- 初始化MessageSource
- 初始化ApplicationEventMultimaster,如果Context中未定義,則使用SimpleApplicationEventMultimaster
- onRefresh方法,SpringBoot中的ServletWebServerApplicationContext實(shí)現(xiàn)類在這個(gè)階段創(chuàng)建WebServer
- 添加實(shí)現(xiàn)ApplicationListener的Bean作為偵聽器
- 完成Bean工廠的初始化,初始化所有剩余的單例Bean
- 完成刷新工作,調(diào)用LifecycleProcessor的onRefresh()方法并發(fā)布ContextRefreshedEvent事件
到了這里,關(guān)于spring啟動(dòng)流程 (1) 流程概覽的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!