文章目录
- ```AbstractApplicationContext#refresh```
- 1. ```prepareRefresh```——刷新前预处理
- 2. ```obtainFreshBeanFactory```——获取```beanFactory```
- 3. ```prepareBeanFactory```——beanFactory赋值,配置一些重要的上下文环境
- 4. ```postProcessBeanFactory```——beanFactory 准备工作完成后进行的后置处理工作。
- 5. ```invokeBeanFactoryPostProcessors```——执行```BeanFactoryPostProcessor```
- 6. ```registerBeanPostProcessors```——注册后置处理器
- 7. ```initMessageSource```——标签国际化资源处理
- 8. ```initApplicationEventMulticaster```——初始化事件派发器
- 9. ```onRefresh```——在容器子类中初始化其他特殊的 bean
- 10. ```registerListeners```——注册监听器
- 11. ```finishBeanFactoryInitialization```——初始化所有非懒加载的单实例 bean
- 12. ```finishRefresh```—— IOC refresh 完成,发布事件
以AnnotationConfigApplicationContext
为例
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
this();
register(componentClasses);
refresh();
}
AbstractApplicationContext#refresh
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// 1. 刷新前预处理
// Prepare this context for refreshing.
prepareRefresh();
// 2. 获取 beanFactory (beanFactory 在构造方法中就 new 出来了)
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 3. beanFactory 的预准备工作(赋值,比如一些上下文环境)
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 4. beanFactory 准备工作完成后进行的后置处理工作。钩子,子类重写这个方法。
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
// 5. 执行 BeanFactoryPostProcessor (beanFactory 标准初始化之后执行)
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 6. 注册后置处理器
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// Initialize message source for this context.
// 7. 标签国际化资源处理,初始化 MessageSource 组件(国际化功能:消息解析,消息绑定)
initMessageSource();
// Initialize event multicaster for this context.
// 8. 初始化事件派发器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 9. 钩子,空方法,供子类实现。初始化其他特殊的 bean。
onRefresh();
// Check for listener beans and register them.
// 10. 注册监听器。
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 11. 初始化所有非懒加载的单实例 bean
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 12. IOC refresh 完成,发布事件
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();
}
}
}
1. prepareRefresh
——刷新前预处理
protected void prepareRefresh() {
// Switch to active.
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
// log ...
// Initialize any placeholder property sources in the context environment.
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties();
// ...
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
initPropertySources
——初始化一些属性设置;钩子,子类实现
protected void initPropertySources() {
// For subclasses: do nothing by default.
}
AbstractEnvironment#validateRequiredProperties
——校验相关属性的合法性
public void validateRequiredProperties() throws MissingRequiredPropertiesException {
this.propertyResolver.validateRequiredProperties();
}
this.earlyApplicationEvents
——保存容器中的一些早期的事件
2. obtainFreshBeanFactory
——获取beanFactory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
GenericApplicationContext#refreshBeanFactory
——刷新beanFactory
AnnotationConfigApplicationContext
继承了GenericApplicationContext
。
protected final void refreshBeanFactory() throws IllegalStateException {
if (!this.refreshed.compareAndSet(false, true)) { // 如果之前刷新过,抛异常
throw new IllegalStateException("GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
}
// 直接使用 beanFactory,说明它在早期就创建了
this.beanFactory.setSerializationId(getId());
}
// 原来 beanFactory 在构造方法中就创建了
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
// getBeanFactory 只是简单的返回 beanFactory
public final ConfigurableListableBeanFactory getBeanFactory() {
return this.beanFactory;
}
bean 的定义已经有了,但是可以在 4. postProcessBeanFactory
和 5. invokeBeanFactoryPostProcessors
中进行修改,关于 bean 定义的加载,将在其他文章中探讨。 TODO
3. prepareBeanFactory
——beanFactory赋值,配置一些重要的上下文环境
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
// 设置 beanFactory 的类加载器
beanFactory.setBeanClassLoader(getClassLoader());
if (!shouldIgnoreSpel) {
// 支持相关的表达式语言的解析
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
}
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
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.ignoreDependencyInterface(ApplicationStartup.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);
// Register early post-processor for detecting inner beans as ApplicationListeners.
// 添加监听检测的处理器
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (!IN_NATIVE_IMAGE && 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()));
}
// Register default environment beans.
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());
}
if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
}
}
4. postProcessBeanFactory
——beanFactory 准备工作完成后进行的后置处理工作。
空方法,是个钩子,供子类实现。模板方法模式。
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
5. invokeBeanFactoryPostProcessors
——执行BeanFactoryPostProcessor
先执行BeanDefinitionRegistryPostProcessor
的postProcessBeanDefinitionRegistry
方法,再执行BeanFactoryPostProcessor
的postProcessBeanFactory
方法。
详见《BeanFactoryPostProcessor & BeanDefinitionRegistryPostProcessor——执行时机》
6. registerBeanPostProcessors
——注册后置处理器
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
PostProcessorRegistrationDelegate#registerBeanPostProcessors
就是把所有的BeanPostProcessor
找出来,分类,排序,注册。
详见《BeanPostProcessor——注册顺序》
7. initMessageSource
——标签国际化资源处理
初始化 MessageSource 组件。主要是国际化功能,如消息解析,消息绑定等。
protected void initMessageSource() {ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// MESSAGE_SOURCE_BEAN_NAME 就是 MessageSource bean 的 id
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());
}
}
// log ...
}
else { // 第一次进来时容器中没有,就要创建,并注册为单实例 bean
// Use empty MessageSource to be able to accept getMessage calls.
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
// 跟一下会发现,其实就是 put 进一个 map 中(singletonObjects, 见 DefaultSingletonBeanRegistry#addSingleton)
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
// log ...
}
}
8. initApplicationEventMulticaster
——初始化事件派发器
流程和上面的initMessageSource
差不多
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// APPLICATION_EVENT_MULTICASTER_BEAN_NAME 就是 ApplicationEventMulticaster bean 的 id
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
// log ...
}
else { // 第一次进来时容器中没有,就要创建,并注册为单实例 bean
SimpleApplicationEventMulticaster simpleApplicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
simpleApplicationEventMulticaster.setApplicationStartup(getApplicationStartup());
this.applicationEventMulticaster = simpleApplicationEventMulticaster;
// 跟一下会发现,其实就是 put 进一个 map 中(singletonObjects, 见 DefaultSingletonBeanRegistry#addSingleton)
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
// log ...
}
}
9. onRefresh
——在容器子类中初始化其他特殊的 bean
空方法,钩子。供子类实现。
protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
}
10. registerListeners
——注册监听器
protected void registerListeners() {
// Register statically specified listeners first.
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
// 事件派发
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
11. finishBeanFactoryInitialization
——初始化所有非懒加载的单实例 bean
这个有些复杂,将在其他文章中详细探讨。详见《IOC原理——非懒加载的单实例bean》
12. finishRefresh
—— IOC refresh 完成,发布事件
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
// Initialize lifecycle processor for this context.
// 实现 LifecycleProcessor 接口。
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
if (!IN_NATIVE_IMAGE) {
LiveBeansView.registerApplicationContext(this);
}
}
相关文章:
BeanFactoryPostProcessor & BeanDefinitionRegistryPostProcessor——执行时机
BeanPostProcessor——注册顺序
IOC原理——非懒加载的单实例bean