本文將通過閱讀AnnotationConfigApplicationContext原始碼,分析Spring啟動流程,
創建AnnotationConfigApplicationContext
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(XxConfig.class);
applicationContext.register(YyConfig.class);
applicationContext.refresh();
XxService xxService = applicationContext.getBean(XxService.class);
核心的啟動邏輯都在refresh方法中,
構造方法
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
AnnotatedBeanDefinitionReader類
定義了多個register方法,用于向Spring容器注冊BeanDefinition,
在創建AnnotatedBeanDefinitionReader時,會向容器注冊幾個注解驅動處理器:
- org.springframework.context.annotation.internalConfigurationAnnotationProcessor: ConfigurationClassPostProcessor
- BeanFactoryPostProcessor實作,用于決議@Configuration類,
- 按優先級排序,因為在@Configuration類中宣告的任何@Bean方法都必須在任何其他BeanFactoryPostProcessor執行之前注冊其對應的BeanDefinition,
- org.springframework.context.annotation.internalAutowiredAnnotationProcessor: AutowiredAnnotationBeanPostProcessor
- BeanPostProcessor實作類,
- @Autowired支持處理器,
- org.springframework.context.annotation.internalCommonAnnotationProcessor: CommonAnnotationBeanPostProcessor
- BeanPostProcessor實作類,
- 支持Resource、PostConstruct、PreDestroy等注解,
- org.springframework.context.event.internalEventListenerProcessor: EventListenerMethodProcessor
- org.springframework.context.event.internalEventListenerFactory: DefaultEventListenerFactory
ClassPathBeanDefinitionScanner類
BeanDefinition掃描器,在類路徑上檢測Bean,并將其注冊到Spring容器中,掃描的類是通過型別過濾器檢測到的,
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相關的ApplicationContext有實作
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物件,
prepareBeanFactory方法
配置BeanFactory的標準背景關系,例如背景關系的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處理器自動將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()));
}
// 注冊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.
在標準初始化之后修改ApplicationContext的內部bean工廠,所有的BeanDefinition都將被加載,但還沒有任何Bean被實體化,這允許在某些ApplicationContext實作中注冊特殊的BeanPostProcessors等,
invokeBeanFactoryPostProcessors方法
實體化并呼叫注冊的所有BeanFactoryPostProcessor,如果指定順序則按照順序呼叫,必須在單例實體化之前呼叫,
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 呼叫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()));
}
}
呼叫BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor,
registerBeanPostProcessors方法
實體化并注冊所有BeanPostProcessor,如果指定順序則按照順序注冊,必須在應用Bean實體化之前呼叫,
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
把BeanPostProcessor實體添加到beanPostProcessors中:
- 從容器獲取所有的BeanPostProcessor Bean
- 按照以下順序注冊:實作了PriorityOrdered介面、實作了Ordered介面、普通BeanPostProcessor、實作MergedBeanDefinitionPostProcessor介面
private static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
initMessageSource方法
國際化,
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時呼叫,在實體化單例之前呼叫,
默認什么都不做,
SpringBoot中的ServletWebServerApplicationContext實作類在這個階段創建WebServer,
registerListeners方法
添加實作ApplicationListener的Bean作為偵聽器,不會影響其他偵聽器,這些偵聽器可以在不使用Bean的情況下添加,
finishBeanFactoryInitialization方法
完成Bean工廠的初始化,初始化所有剩余的單例Bean,
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方法
完成重繪作業,呼叫LifecycleProcessor的onRefresh()方法并發布ContextRefreshedEvent事件,
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);
}
啟動流程
- 創建AnnotationConfigApplicationContext物件
- 創建AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner
- 向容器注冊幾個注解驅動處理器:ConfigurationClassPostProcessor, AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor等
- 呼叫applicationContext.register(XxConfig.class)注冊配置類
- 呼叫refresh()方法:
- prepareRefresh方法準備作業:初始化PropertySources、validateRequiredProperties等
- Refresh the internal beanFactory
- 配置BeanFactory的標準背景關系,例如背景關系的ClassLoader和后置處理器
- 實體化并呼叫注冊的所有BeanFactoryPostProcessor,如果指定順序則按照順序呼叫,必須在單例實體化之前呼叫
- 實體化并注冊所有BeanPostProcessor,如果指定順序則按照順序注冊,必須在應用Bean實體化之前呼叫
- 初始化MessageSource
- 初始化ApplicationEventMultimaster,如果Context中未定義,則使用SimpleApplicationEventMultimaster
- onRefresh方法,SpringBoot中的ServletWebServerApplicationContext實作類在這個階段創建WebServer
- 添加實作ApplicationListener的Bean作為偵聽器
- 完成Bean工廠的初始化,初始化所有剩余的單例Bean
- 完成重繪作業,呼叫LifecycleProcessor的onRefresh()方法并發布ContextRefreshedEvent事件
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/556011.html
標籤:其他
下一篇:返回列表