相关源码注释
ApplicationContext
Spring 5 DefaultResourceLoader 源码注释
Spring 5 AbstractApplicationContext 源码注释
BeanFactory
Spring 5 SimpleAliasRegistry 源码注释
Spring 5 DefaultSingletonBeanRegistry 源码注释
Spring 5 FactoryBeanRegistrySupport 源码注释
Spring 5 AbstractBeanFactory 源码注释
Spring 5 AbstractAutowireCapableBeanFactory 源码注释
Spring 5 DefaultLisbaleBeanFactory 源码注释
UML类图
源码
/**
* Abstract implementation of the {@link org.springframework.context.ApplicationContext}
* interface. Doesn't mandate the type of storage used for configuration; simply
* implements common context functionality. Uses the Template Method design pattern,
* requiring concrete subclasses to implement abstract methods.
* <p>
* {@link org.springframework.context.ApplicationContext}接口的抽象实现。
* 不强制用于配置的存储类型;简单实现通用上下文功能。使用模板方法设计模式,
* 需要具体的子类来实现抽象方法
* </p>
*
* <p>In contrast to a plain BeanFactory, an ApplicationContext is supposed
* to detect special beans defined in its internal bean factory:
* Therefore, this class automatically registers
* {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor BeanFactoryPostProcessors},
* {@link org.springframework.beans.factory.config.BeanPostProcessor BeanPostProcessors},
* and {@link org.springframework.context.ApplicationListener ApplicationListeners}
* which are defined as beans in the context.
* <p>
* 与具体的BeanFactory相反,一个ApplicationContext应该检查其内部bean工厂中
* 定义的特殊bean:因此,这些类会被自动注册:
* {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor BeanFactoryPostProcessors},
* {@link org.springframework.beans.factory.config.BeanPostProcessor BeanPostProcessors},
* {@link org.springframework.context.ApplicationListener ApplicationListeners}
* 在上下文中被定义为bean
* </p>
*
* <p>A {@link org.springframework.context.MessageSource} may also be supplied
* as a bean in the context, with the name "messageSource"; otherwise, message
* resolution is delegated to the parent context. Furthermore, a multicaster
* for application events can be supplied as an "applicationEventMulticaster" bean
* of type {@link org.springframework.context.event.ApplicationEventMulticaster}
* in the context; otherwise, a default multicaster of type
* {@link org.springframework.context.event.SimpleApplicationEventMulticaster} will be used.
* <p>
* A {@link org.springframework.context.MessageSource}可以同时被提供作为一个
* 上下文中bean,名称为'messageSource';否,将消息解析委托给父级上下文。此外,
* 还有一个提供用于应用程序时间的多播器以{@link org.springframework.context.event.ApplicationEventMulticaster}
* 类型,名称为'applicationEventMulticaster'在上下文中;除此之外,还使用到了类型为
* {@link org.springframework.context.event.SimpleApplicationEventMulticaster}的默认多播器
* </p>
* <p>Implements resource loading by extending
* {@link org.springframework.core.io.DefaultResourceLoader}.
* Consequently treats non-URL resource paths as class path resources
* (supporting full class path resource names that include the package path,
* e.g. "mypackage/myresource.dat"), unless the {@link #getResourceByPath}
* method is overridden in a subclass.
* <p>
* 通过扩展 {@link org.springframework.core.io.DefaultResourceLoader}来实现资源加载。
* 因此,将非URL资源路径视为类路径资源(支持包含程序包路径的完整类路径资源名称,如
* 'mypackage/myresource.dat'),除非 {@link #getResourceByPath}在子类中被覆盖
* </p>
* @author Rod Johnson
* @author Juergen Hoeller
* @author Mark Fisher
* @author Stephane Nicoll
* @author Sam Brannen
* @since January 21, 2001
* @see #refreshBeanFactory
* @see #getBeanFactory
* @see org.springframework.beans.factory.config.BeanFactoryPostProcessor
* @see org.springframework.beans.factory.config.BeanPostProcessor
* @see org.springframework.context.event.ApplicationEventMulticaster
* @see org.springframework.context.ApplicationListener
* @see org.springframework.context.MessageSource
*/
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
/**
* Name of the MessageSource bean in the factory.
* If none is supplied, message resolution is delegated to the parent.
* <p>MessageSource在工厂中的bean名.如果未提供,则将消息解析位委托给父类</p>
* @see MessageSource
*/
public static final String MESSAGE_SOURCE_BEAN_NAME = "messageSource";
/**
* Name of the LifecycleProcessor bean in the factory.
* If none is supplied, a DefaultLifecycleProcessor is used.
* <p>
* LifecycleProcessor在工厂中的bean名。如果未提供,就用DefaultLifecycleProcessor
* </p>
* @see org.springframework.context.LifecycleProcessor
* @see org.springframework.context.support.DefaultLifecycleProcessor
*/
public static final String LIFECYCLE_PROCESSOR_BEAN_NAME = "lifecycleProcessor";
/**
* Name of the ApplicationEventMulticaster bean in the factory.
* If none is supplied, a default SimpleApplicationEventMulticaster is used.
* <p>
* ApplicationEventMulticaster在工厂中的bean名。如果为提供,
* 就用默认的SimpleApplicationEventMulticaster
* </p>
* @see org.springframework.context.event.ApplicationEventMulticaster
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
static {
// Eagerly load the ContextClosedEvent class to avoid weird classloader issues
// on application shutdown in WebLogic 8.1. (Reported by Dustin Woods.)
// 饿汉式加载ContextClosedEvent类,以避免出现奇怪的类加载问题
// Weblogic8.1中应用程序关闭时发生的故障。(达斯汀·伍兹报道)
ContextClosedEvent.class.getName();
}
/** Logger used by this class. Available to subclasses. <p>此类用于日志记录。可用于子类</p> */
protected final Log logger = LogFactory.getLog(getClass());
/**
* Unique id for this context, if any.
* <p>此上下文的唯一ID(如果有)</p>
* <p>ObjectUtils.identityToString:可得到(obj的全类名+'@'+obj的hashCode的十六进制字符串)</p>
* */
private String id = ObjectUtils.identityToString(this);
/**
* Display name.
* <p>展示名</p>
* <p>ObjectUtils.identityToString:可得到(obj的全类名+'@'+obj的hashCode的十六进制字符串)</p>
* */
private String displayName = ObjectUtils.identityToString(this);
/** Parent context. <p>父级上下文</p>*/
@Nullable
private ApplicationContext parent;
/** Environment used by this context.
* <p>此上下文使用的环境,SpringBoot默认使用StandardServletEnvironment</p> */
@Nullable
private ConfigurableEnvironment environment;
/** BeanFactoryPostProcessors to apply on refresh.
* <p>BeanFactoryPostProcessors 应用于刷新</p>
* */
private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors = new ArrayList<>();
/**
* System time in milliseconds when this context started.
* <p>此上下文启动时的系统时间(以毫秒为单位)</p>
* */
private long startupDate;
/**
* Flag that indicates whether this context is currently active.
* <p>指示此上下文当前是否处于活动状态的标记,该变量是线程安全的</p>
* */
private final AtomicBoolean active = new AtomicBoolean();
/**
* Flag that indicates whether this context has been closed already.
* <p>指示此上下文是否已经关闭的标记,该变量是线程安全的</p>
* */
private final AtomicBoolean closed = new AtomicBoolean();
/**
* Synchronization monitor for the "refresh" and "destroy".
* <p>'refresh'和'destory'的同步监控</p>
* */
private final Object startupShutdownMonitor = new Object();
/** Reference to the JVM shutdown hook, if registered. */
@Nullable
private Thread shutdownHook;
/**
* ResourcePatternResolver used by this context.
* <p>默认得到的是PathMatchingResourcePatternResolver, 这个一个支持Ant-style位置模式的类</p>
* Ant-styple:https://blog.csdn.net/my__sun_/article/details/76444435
* */
private ResourcePatternResolver resourcePatternResolver;
/** LifecycleProcessor for managing the lifecycle of beans within this context. */
@Nullable
private LifecycleProcessor lifecycleProcessor;
/**
* MessageSource we delegate our implementation of this interface to.
* <p>我们将此接口的实现委托给 MessageSource </p>
* */
@Nullable
private MessageSource messageSource;
/**
* Helper class used in event publishing.
* <p>事件发布中使用的 helper 类</p>
* */
@Nullable
private ApplicationEventMulticaster applicationEventMulticaster;
/**
* Statically specified listeners.
* 静态指定的监听器集
* */
private final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();
/**
* Local listeners registered before refresh.
* <p>刷新之前已注册本地侦听器</p>
* */
@Nullable
private Set<ApplicationListener<?>> earlyApplicationListeners;
/**
* ApplicationEvents published before the multicaster setup.
* <p>在多播程序设置之前发布的ApplicationEvent</p>
* */
@Nullable
private Set<ApplicationEvent> earlyApplicationEvents;
/**
* Create a new AbstractApplicationContext with no parent.
* 创建一个新的无父类的AbatractApplciationContext
*/
public AbstractApplicationContext() {
//默认得到的是PathMatchingResourcePatternResolver, 这个一个支持Ant-style位置模式的类
//Ant-styple:https://blog.csdn.net/my__sun_/article/details/76444435
this.resourcePatternResolver = getResourcePatternResolver();
}
/**
* Create a new AbstractApplicationContext with the given parent context.
* @param parent the parent context
*/
public AbstractApplicationContext(@Nullable ApplicationContext parent) {
///默认将resourcePatternResolver赋值为PathMatchingResourcePatternResolver,
// 这个一个支持Ant-style位置模式的类
// Ant-styple:https://blog.csdn.net/my__sun_/article/details/76444435
this();
//设置应用程序上下文的父级
//如果父级引用程序上下文不为null且它的environment是ConfigurableEnvironment 的实例,
// 将会和子级的应用程序上下文进行合并
setParent(parent);
}
//---------------------------------------------------------------------
// Implementation of ApplicationContext interface
//---------------------------------------------------------------------
/**
* Set the unique id of this application context.
* <p>设置此应用程序上下文的唯一ID</p>
*
* <p>Default is the object id of the context instance, or the name
* of the context bean if the context is itself defined as a bean.
* <p>默认值为上下文实例的对象ID,如果上下文定义为Bean,则为上下文bean的名称。</p>
* @param id the unique id of the context
*/
@Override
public void setId(String id) {
this.id = id;
}
@Override
public String getId() {
return this.id;
}
@Override
public String getApplicationName() {
return "";
}
/**
* Set a friendly name for this context.
* <p>为此上下文设置一个友好的名称</p>
*
* Typically done during initialization of concrete context implementations.
* <p>通常在初始化具体上下文实现期间完成</p>
*
* <p>Default is the object id of the context instance.
* <p>默认值为上下文实例的对象Id</p>
*/
public void setDisplayName(String displayName) {
//如果displayName为null或者为空字符串,抛出异常
Assert.hasLength(displayName, "Display name must not be empty");
this.displayName = displayName;
}
/**
* Return a friendly name for this context.
* <p>返回此上下文的友好名称</p>
* @return a display name for this context (never {@code null})
* -- 此上下文的显示名称(不要{@code null})
*/
@Override
public String getDisplayName() {
return this.displayName;
}
/**
* Return the parent context, or {@code null} if there is no parent
* (that is, this context is the root of the context hierarchy).
* <p>返回父上下文,如果没有父级,则返回{@code null}(也就是说,此上下文层次结构
* 的根)</p>
*/
@Override
@Nullable
public ApplicationContext getParent() {
return this.parent;
}
/**
* Set the {@code Environment} for this application context.
* <p>Default value is determined by {@link #createEnvironment()}. Replacing the
* default with this method is one option but configuration through {@link
* #getEnvironment()} should also be considered. In either case, such modifications
* should be performed <em>before</em> {@link #refresh()}.
* @see org.springframework.context.support.AbstractApplicationContext#createEnvironment
*/
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
this.environment = environment;
}
/**
* Return the {@code Environment} for this application context in configurable
* form, allowing for further customization.
* <p>以可配置的形式返回此应用程序上下文的{@code Environment},以便进行进一步的自定义。</p>
* <p>If none specified, a default environment will be initialized via
* {@link #createEnvironment()}.
* <p>如果未指定,则默认环境将通过{@link #createEnvironment()}进行初始化。</p>
*/
@Override
public ConfigurableEnvironment getEnvironment() {
//如果当前上下文没有environment对象
if (this.environment == null) {
//创建一个新的StandardEnvironment
this.environment = createEnvironment();
}
return this.environment;
}
/**
* Create and return a new {@link StandardEnvironment}.
* <p>创建并返回一个新的{@link StandardEnvironment}</p>
* <p>Subclasses may override this method in order to supply
* a custom {@link ConfigurableEnvironment} implementation.
* <p>子类可以重新此方法,以提供一个自定义{@link ConfigurableEnvironment}实现</p>
*/
protected ConfigurableEnvironment createEnvironment() {
//StandardEnvironment:使用与"标准"(即非网络)应用程序的Environment实现,
// 除了ConfigurableEnvironment的常用功能(例如属性解析和配置文件相关的操作)之外,
// 此实现还配置了两个默认的属性源,将按一下顺序进行搜索:
// 1. system properties 系统属性
// 2. system environment variables 系统环境属性
return new StandardEnvironment();
}
/**
* Return this context's internal bean factory as AutowireCapableBeanFactory,
* if already available.
* @see #getBeanFactory()
*/
@Override
public AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException {
return getBeanFactory();
}
/**
* Return the timestamp (ms) when this context was first loaded.
*/
@Override
public long getStartupDate() {
return this.startupDate;
}
/**
* Publish the given event to all listeners.
* <p>将给定事件发布到所有监听器。</p>
* <p>Note: Listeners get initialized after the MessageSource, to be able
* to access it within listener implementations. Thus, MessageSource
* implementations cannot publish events.
* <p>注意:侦听器在MessageSource之后被初始化,以便能够在侦听器实现中访问它。
* 因此,MessageSource实现不能发布事件</p>
* @param event the event to publish (may be application-specific or a
* standard framework event)
* -- 要发布的事件(可能是特定于应用程序的事件或标准框架事件)
*/
@Override
public void publishEvent(ApplicationEvent event) {
publishEvent(event, null);
}
/**
* Publish the given event to all listeners.
* <p>将给定事件发布到所有监听器。</p>
* <p>Note: Listeners get initialized after the MessageSource, to be able
* to access it within listener implementations. Thus, MessageSource
* implementations cannot publish events.
* <p>注意:侦听器在MessageSource之后被初始化,以便能够在侦听器实现中访问它。 因此,MessageSource实现不能发布事件</p>
* @param event the event to publish (may be an {@link ApplicationEvent}
* or a payload object to be turned into a {@link PayloadApplicationEvent})
* -- 要发布的事件(可能是特定于应用程序的事件或标准框架事件)
*/
@Override
public void publishEvent(Object event) {
publishEvent(event, null);
}
/**
* <p>将 event 多播到所有适合的监听器。如果 event 不是 ApplicationEvent 实例,会将其封装成 PayloadApplicationEvent 对象
* 再进行多播。</p>
* <p>当上下文的多播器没有初始化时,会将event暂时保存起来,待多播器初始化后才将缓存的event进行多播</p>
* Publish the given event to all listeners.
* <p>将给定事件发布到所有监听器</p>
* @param event the event to publish (may be an {@link ApplicationEvent}
* or a payload object to be turned into a {@link PayloadApplicationEvent})
* -- 要发布的事件(可能是特定于应用程序的事件或标准框架事件)
* @param eventType the resolved event type, if known -- 已解析的事件类型(如果已知)
* @since 4.2
*/
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
//如果 event 为null,抛出异常
Assert.notNull(event, "Event must not be null");
// Decorate event as an ApplicationEvent if necessary
// 装饰事件作为一个应用事件,如果有必要
ApplicationEvent applicationEvent;
//如果 event 是 ApplicationEvent 的 实例
if (event instanceof ApplicationEvent) {
//将 event 强转为 ApplicationEvent 对象
applicationEvent = (ApplicationEvent) event;
}
else {
//PayloadApplicationEvent:携带任意有效负载的ApplicationEvent。
//创建一个新的 PayloadApplicationEvent
applicationEvent = new PayloadApplicationEvent<>(this, event);
//如果 eventType 为 null
if (eventType == null) {
//将 applicationEvent 转换为 PayloadApplicationEvent 对象,引用其 ResolvableType 对象
eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
}
}
// Multicast right now if possible - or lazily once the multicaster is initialized
// 如果可能的话,现在就进行组播——或者在组播初始化后延迟
// earlyApplicationEvents:在多播程序设置之前发布的ApplicationEvent
// 如果 earlyApplicationEvents 不为 null,这种情况只在上下文的多播器还没有初始化的情况下才会成立, 会将 applicationEvent
// 添加到 earlyApplicationEvents 保存起来,待多博器初始化后才继续进行多播到适当的监听器
if (this.earlyApplicationEvents != null) {
//将applicationEvent添加到 earlyApplicationEvents
this.earlyApplicationEvents.add(applicationEvent);
}
else {
//多播applicationEvent到适当的监听器
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
}
// Publish event via parent context as well...
// 通过父上下文发布事件
// 如果 parent 不为 null
if (this.parent != null) {
//如果 parent 是 AbstractApplicationContext 的实例
if (this.parent instanceof AbstractApplicationContext) {
//将 event 多播到所有适合的监听器。如果 event 不是 ApplicationEvent 实例,会将其封装成 PayloadApplicationEvent 对象再进行多播
((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
}
else {
//通知与event事件应用程序注册的所有匹配的监听器
this.parent.publishEvent(event);
}
}
}
/**
* Return the internal ApplicationEventMulticaster used by the context.
* <p>返回上下文使用的内部 ApplicationEventMulticater </p>
* @return the internal ApplicationEventMulticaster (never {@code null})
* -- 内部的 ApplicationEventMulticaster (永不为 null)
* @throws IllegalStateException if the context has not been initialized yet
* -- 如果上下文尚未初始化
*/
ApplicationEventMulticaster getApplicationEventMulticaster() throws IllegalStateException {
//如果 applicationEventMulticaster 为 null
if (this.applicationEventMulticaster == null) {
//抛出非法状态异常:ApplicationEventMulticaster 没有被初始化 - 在通过上下文多播事件之前先调用 'refresh'方法
throw new IllegalStateException("ApplicationEventMulticaster not initialized - " +
"call 'refresh' before multicasting events via the context: " + this);
}
//返回 applicationEventMulticaster
return this.applicationEventMulticaster;
}
/**
* Return the internal LifecycleProcessor used by the context.
* <p>返回 上下文使用的内部生命周期处理器</p>
* @return the internal LifecycleProcessor (never {@code null})
* -- 内部生命周期处理器(从不为 null)
* @throws IllegalStateException if the context has not been initialized yet
* -- 如果上下文还没有初始化
*/
LifecycleProcessor getLifecycleProcessor() throws IllegalStateException {
//如果 lifecycleProcessor 为 null
if (this.lifecycleProcessor == null) {
//抛出 非法状态异常:生命周期处理器未初始化 - 在通过上下文调用生命周期方法调用'refresh'
throw new IllegalStateException("LifecycleProcessor not initialized - " +
"call 'refresh' before invoking lifecycle methods via the context: " + this);
}
//返回 lifecycleProcessor
return this.lifecycleProcessor;
}
/**
* Return the ResourcePatternResolver to use for resolving location patterns
* into Resource instances. Default is a
* {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver},
* supporting Ant-style location patterns.
* <p>返回ResourcePatternResolver,用于将位置模式解析为Resouce实例 。默认值
* 为{@link org.springframework.core.io.support.PathMatchingResourcePatternResolver},
* 支持Ant样式的位置模式</p>
*
* <p>Can be overridden in subclasses, for extended resolution strategies,
* for example in a web environment.
* <p>可以在子类中覆盖,以用于扩展解析策略,例如在Web环境中,可以在子类中覆盖它</p>
*
* <p><b>Do not call this when needing to resolve a location pattern.</b>
* Call the context's {@code getResources} method instead, which
* will delegate to the ResourcePatternResolver.
*
* <p>在需要解析位置模式时不要调用此方法,而是调用上下文的{@code getResources}方法,
* 该方法将委托给ResourcePatternResolver</p>
*
* @return the ResourcePatternResolver for this context
* -- 此上下文的ResourcePatternResolver
* @see #getResources
* @see org.springframework.core.io.support.PathMatchingResourcePatternResolver
*/
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}
//---------------------------------------------------------------------
// Implementation of ConfigurableApplicationContext interface
//---------------------------------------------------------------------
/**
* Set the parent of this application context.
* -设置应用程序上下文的父级
* <p>The parent {@linkplain ApplicationContext#getEnvironment() environment} is
* {@linkplain ConfigurableEnvironment#merge(ConfigurableEnvironment) merged} with
* this (child) application context environment if the parent is non-{@code null} and
* its environment is an instance of {@link ConfigurableEnvironment}.
* <p>如果父级引用程序上下文不为null且它的environment是{@link ConfigurableEnvironment}
* 的实例,将会和子级的应用程序上下文进行合并</p>
* @see ConfigurableEnvironment#merge(ConfigurableEnvironment)
*/
@Override
public void setParent(@Nullable ApplicationContext parent) {
this.parent = parent;
if (parent != null) {
Environment parentEnvironment = parent.getEnvironment();
if (parentEnvironment instanceof ConfigurableEnvironment) {
//将给定的父环境的活动配置文件,默认配置文件和属性源追加到此(子)环境各自集合中
getEnvironment().merge((ConfigurableEnvironment) parentEnvironment);
}
}
}
@Override
public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor) {
Assert.notNull(postProcessor, "BeanFactoryPostProcessor must not be null");
this.beanFactoryPostProcessors.add(postProcessor);
}
/**
* Return the list of BeanFactoryPostProcessors that will get applied
* to the internal BeanFactory.
* <p>返回将应用于内部BeanFactory的BeanFactoryPostPorcessor列表</p>
*/
public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
return this.beanFactoryPostProcessors;
}
@Override
public void addApplicationListener(ApplicationListener<?> listener) {
Assert.notNull(listener, "ApplicationListener must not be null");
if (this.applicationEventMulticaster != null) {
this.applicationEventMulticaster.addApplicationListener(listener);
}
this.applicationListeners.add(listener);
}
/**
* Return the list of statically specified ApplicationListeners.
* <p>返回静态指定的applicationListenere列表</p>
*/
public Collection<ApplicationListener<?>> getApplicationListeners() {
return this.applicationListeners;
}
@Override
public void refresh() throws BeansException, IllegalStateException {
//同步,startupShutdownMonitor只是一个普通的object对象,
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
// 准备该上下文的刷新
// p:准备该上下文以进行刷新,设置其启动日期和activie标记以及
// 执行属性源的任何 初始化。还有监听器都初始化
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 告诉子类刷新新内部bean工厂
//对此上下文的基础bean工厂进行实际刷新,关闭前一个bean工厂(如果有),
// 并为上下文生命周期的下一个阶段初始化一个新的bean工厂,并使用XmlBeanDefinitionReader
// 将bean定义加载给bean工厂中
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 准备这种情况下使用的bean工厂
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 允许在上下文子类中对bean工厂进行后处理
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 调用在上下文中注册为bean的工厂处理器
// 实例化并调用所有注册BeanFactoryPostProcess bean,并遵从显式顺序(如果给定的话)
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册拦截Bean创建的 BeanPostProcessor
// 实例化和注册所有 BeanPostProcessor 类型的Bean对象,如果给定的话,遵循显示顺序.
// 必须在应用程序Bean的任何实例化之前调用
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 为此上下文初始化消息源
// 从当前BeanFactory中获取名为 'messageSource' 的 MessageSource 类型的Bean对象,如果没有找到,就创建 一个
// DelegatingMessageSource 对象作为该上下文的 messageSource 属性值,并将该上下文的 messageSource 注册到 该
// 上下文的BeanFactory中。
// 默认对该上下文的messageSource设置父级messageSource,父级messageSource为父级上下文的messageSoure属性对象
// 或者父级上下文本身
initMessageSource();
// Initialize event multicaster for this context.
// 为此上下文初始化事件多播器
// 从从beanFactory中获取名为 'applicationEventMulticaster' 的 ApplicationEventMulticaster 类型的Bean对象,
// 引用到 该上下文的 applicationEventMulticaster 属性,如果获取不到,就新建一个
// SimpleApplicationEventMulticaster 实例 引用 到 上下文的 applicationEventMulticaster 属性 中
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 初始化特定上下文子类中的其他特殊Bean
onRefresh();
// Check for listener beans and register them.
// 检查监听器Bean并注册它们
//注册静态指定的监听器和beanFactory内的监听器Bean对象【不会导致监听器Bean对象实例化,仅记录其Bean名】到当前上
// 下文 的多播器,然后发布在多播程序设置之前发布的ApplicationEvent集到各个监听器中
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.`
// 实例化所有剩余的(非延迟初始化)的单例
//完成这个上下文BeanFactory的初始化,初始化所有剩余的 单例(非延迟初始化) Bean对象
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 最后一步:发布相应的事件
// 1. 清空在资源加载器中的所有资源缓存
// 2. 初始化 LifecycleProcessor.如果上下文中找到 'lifecycleProcessor' 的 LifecycleProcessor Bean对象, 则使用 DefaultLifecycleProcessor
// 3. 将刷新传播到生命周期处理器
// 4. 新建 ContextRefreshedEvent 事件对象,将其发布到所有监听器。
// 5. 注册 当前上下文 到 LiveBeansView,以支持 JMX 服务
finishRefresh();
}
catch (BeansException ex) {//捕捉在初始化Bean时抛出的 Bean异常
//如果当前日志级别时 警告
if (logger.isWarnEnabled()) {
// 在上下文初始化过程中遇到异常 - 尝试取消刷新
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
// 销毁已经创建的单例,以避免悬空资源
// 默认实现此上下文中销毁所有缓存的单例,调用DisposableBean.destroy()和 或指定的'destory-method'
destroyBeans();
// Reset 'active' flag.
// 重置 'active' 标记
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...
// 在 Spring的核心中重置常见的自省缓存,因为我们可能不再需要单例Bean的元数据了。
//删除ReflectionUtils,AnnotationUtils,ResolvableType的缓存,清除当前的类加载器的自省缓存,
// 删除该类加载器下 所有类的自省结果,并从接受列表中删除类加载器(及其子类)
resetCommonCaches();
}
}
}
/**
* <p>ApplicationContext刷新前的准备工作:
* <ol>
* <li>设置上下文启动时的系统时间,startupDate</li>
* <li>设置上下文为不关闭状态,closed</li>
* <li>设置上下文为活动状态,active</li>
* <li>根据日志级别打印日志,提示准备刷新ApplicationContext</li>
* <li>创建Environment对象,默认情况下Environment对象是StandardEnvironment对象</li>
* <li>提供一个钩子方法,交由子类替换任何存根属性源。默认情况下子类GenericWebApplicationContext,
* 通过该方法设置sources中的servletContextInitParams和servletConfigInitParams属性,以供更方便的
* 形式获取SerlvetContext。</li>
* <li>初始化用于存储已注册本地侦听器的LinkedHashSet集合,earlyApplicationListeners</li>
* <li>初始化用于收集早期的ApplicationEvents的LinkeHashSet集合,earlyApplicationEvents</li>
* </ol>
* </p>
* Prepare this context for refreshing, setting its startup date and
* active flag as well as performing any initialization of property sources.
* <p>准备该上下文以进行刷新,设置其启动日期和activie标记以及执行属性源的任何
* 初始化。</p>
*/
protected void prepareRefresh() {
// Switch to active. 切换到互动状态
//p:设置上下文启动时的系统时间
this.startupDate = System.currentTimeMillis();
//p:设置上下文为不关闭状态,该变量是线程安全的
this.closed.set(false);
///p:设置上下文为活动状态,该变量是线程安全的
this.active.set(true);
//根据日志级别打印日志
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// Initialize any placeholder property sources in the context environment.
// 在上下文环境中初始化任何占位符属性源
//p:这个一个钩子方法,用于交由子类替换任何存根属性源
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
// 验证所有标记为必须的属性都是可解析的,请参见
// ConfigurablePropertyResolver#setRequiredProperties方法,
// p:该方法的默认实现是AbstractPropertyResolver类
// p:只是验证要必须要有的属性不会为null,验证不通过会抛出MissingRequiredPropertiesException
// SpringBoot默认情况下不存在必要的属性
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners... 存储预刷新的ApplicationListeners
// p:初始化earlyApplicationListeners
if (this.earlyApplicationListeners == null) {
//p:LinkedHashSet是Set集合的一个实现,具有set集合不重复的特点,同时具有
// 可预测的迭代顺序,也就是我们插入的顺序,并且linkedHashSet是一个非线程安全的集合。
// 如果有多个线程同时访问当前linkedhashset集合容器,并且有一个线程对当前容器中的元素
// 做了修改,那么必须要在外部实现同步保证数据的冥等性
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
// 将本地应用程序监听器重置为预刷新状态
// p:清空静态指定的监听器集
this.applicationListeners.clear();
// p:将 刷新之前已注册本地侦听器 全部添加到静态指定的监听器集中
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
// 允许收集早期的ApplicationEvents,一旦多播器可用就发布
this.earlyApplicationEvents = new LinkedHashSet<>();
}
/**
* <p>Replace any stub property sources with actual instances.
* <p>用实际实例替换任何存根属性源</p>
* @see org.springframework.core.env.PropertySource.StubPropertySource
* @see org.springframework.web.context.support.WebApplicationContextUtils#initServletPropertySources
*/
protected void initPropertySources() {
// For subclasses: do nothing by default. 对于子类:默认情况下不执行任何操作
}
/**
* <p>
* 获取新的Bean工厂:
* <ol>
* <li>调用供子类实现refreshBeanFactory()方法执行实际的配置加载</li>
* <li>调用供子类实现的getBeanFactory()方法获取子类提供的Bean工厂</li>
* </ol>
* </p>
* Tell the subclass to refresh the internal bean factory.
* <p>告诉子类刷新内部bean工厂。</p>
* @return the fresh BeanFactory instance --新的BeanFactorty实例
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//调用子类实现方法执行实际的配置加载
refreshBeanFactory();
//返回子类提供的Bean工厂,
return getBeanFactory();
}
/**
* <p>对bean工厂做准备工作:
* <ol>
* <li>设置beanFactory的bean的类加载器,通常是当前线程的上下文类加载器,AppClassLoader</li>
* <li>为bean定义值中的表达式指定解析策略,这里设置的是标准的Spring EL表达式解析器,StandardBeanExpressionResolver</li>
* <li>添加属性编辑器到bean工厂,ResourceEditorRegistrar</li>
* <li>为bean工厂添加 为实现了某种Aware接口的bean设置ApplicationContext中相应的属性的BeanPostProcessor,ApplicationContextAwareProcessor</li>
* <li>忽略 EnvironmentAware,EmbeddedValueResolverAware,ResourceLoaderAware,ApplicationEventPublisherAware,MessageSourceAware
* ApplicationContextAware依赖接口进行自动装配</li>
* <li>添加自动装配对象:BeanFactory,ResourceLoader,ApplicationEventPublisher,ApplicationContext</li>
* <li>如果该bean工厂包含具有给定名称的BeanDefinition对象或外部注册的singleton实例,会添加用于回调LoadTimeWeaverAware#setLoadTimeWeaver(LoadTimeWeaver)
* 方法的BeanPostProcessor,以及设置一个ContextTypeMatchClassLoader的临时类加载器用于对每个调用loadClass的类【除指定排除类外】,都会新建一个
* ContextOverridingClassLoader类加载器进行加载,并对每个类的字节缓存起来,以便在父类ClassLoader中拾取 最近加载的类</li>
* <li>注册environment,systemProperties,systemEnvironment单例对象到该工厂</li>
* </ol>
* </p>
* Configure the factory's standard context characteristics,
* such as the context's ClassLoader and post-processors.
* <p>配置工厂的标准上下文特征,例如上下文的ClassLoader和后处理器。</p>
* @param beanFactory the BeanFactory to configure -- 要配置的BeanFactory
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
// 告诉内部bean工厂使用上下文的类加载器等
//设置beanFactory的bean的类加载器,通常是当前线程的上下文类加载器
beanFactory.setBeanClassLoader(getClassLoader());
//为bean定义值中的表达式指定解析策略,这里设置的是标准的Spring EL表达式解析器
//StandardBeanExpressionResolver:用于解析SpEL表达式的解析器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
//添加属性编辑器到bean工厂,ResourceEditorRegistrar:属性编辑器的注册器,里面默认提供了一下简单通用常用类型的属性编辑器
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
//使用上下文回调配置Bean工厂
//为bean工厂添加ApplicationContextAwareProcessor
//ApplicationContextAwareProcessor:一个Spring内部工具,它实现了接口BeanPostProcessor,用于向实现了如下某种Aware接口
// 的bean设置ApplicationContext中相应的属性:EnvironmentAware,EmbeddedValueResolverAware,ResourceLoaderAware
// ApplicationEventPublisherAware,MessageSourceAware,ApplicationContextAware,
// 如果bean实现了以上接口中的某几个,那么这些接口方法调用的先后顺序就是上面接口排列的先后顺序。
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//忽略 EnvironmentAware 依赖接口进行自动装配
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
//忽略 EmbeddedValueResolverAware 依赖接口进行自动装配
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
//忽略 ResourceLoaderAware 依赖接口进行自动装配
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
//忽略 ApplicationEventPublisherAware 依赖接口进行自动装配
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
//忽略 MessageSourceAware 依赖接口进行自动装配
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
//忽略 ApplicationContextAware 依赖接口进行自动装配
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// BeanFactory接口未在普通工厂中注册为可解析类型
// MessageSource registered (and found for autowiring) as a bean.
// MessageSource注册为Bean(并发现用于自定装配)
//用beanFactory对象注册一个BeanFactory类型
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
//用本类对象注册一个ResourceLoader类型
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
//用本类对象注册一个ApplicationEventPublisher类型
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
//用本类对象注册一个ApplicationContext类型
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
// 注册早期的后处理器以将内部bean检测为ApplicationListeners
// ApplicationListenerDetector:该BeanPostProcessor检测那些实现了接口ApplicationListener的bean,在它们创建时初始化之后,
// 将它们添加到应用上下文的事件多播器上;并在这些ApplicationListener bean销毁之前,
// 将它们从应用上下文的事件多播器上移除。
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// 标记1 - start
// Detect a LoadTimeWeaver and prepare for weaving, if found.
// 如果发现LoadTimeWeaver,请准备编制
// beanFactory.containBean除了检查bean对象是否存在,还可以判断BeanDefinition对象是否存在,存在一样会返回true。
// 所以这里是是检查有没有loadTimeWeaver的BeanDefinition对象
// SpringBoot默认情况下该bean工厂不包含loadTimeWeaver的bean定义或外部注册的singleton实例
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
//LoadTimeWeaverAwareProcessor只是用实现了LoadTimeWeaverAware接口的bean
// // 回调LoadTimeWeaverAware.setLoadTimeWeaver(LoadTimeWeaver)方法
// // 参考博客:https://blog.csdn.net/weixin_34112208/article/details/89750308
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
//设置一个临时的ClassLoader以进行匹配
//ContextTypeMatchClassLoader:该类加载器破坏了双亲委派机制,除指定排除类外,
// 对每个调用loadClass的类,都会新建一个ContextOverridingClassLoader类加载器进行
// 加载,并对每个类的字节缓存起来,以便在父类ClassLoader中拾取 最近加载的类型
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// 标记1 - end
// Register default environment beans. - 注册默认的环境bean
//如果bean工厂中没有包含名为'environment'的bean,(忽略在祖先上下文定义的bean)
//SpringBoot默认情况下该bean工厂是否包含loadTimeWeaver的bean定义或外部注册的singleton实例
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
//获取该ApplicationContext的环境对象,注册到bean工厂中,命名为'environment'
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
//如果bean工厂中没有包含名为'systemProperties'的bean,(忽略在祖先上下文定义的bean)
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
//获取该ApplicationContext的环境对象的系统属性Map,注册到bean工厂中,命名为'systemProperties'
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
//如果bean工厂中没有包含名为'systemEnvironment'的bean,(忽略在祖先上下文定义的bean)
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
//获取该ApplicationContext的环境对象的系统环境属性Map,注册到bean工厂中,命名为'systemProperties'
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
/**
* 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.
* <p>标准初始化后,修改应用程序上下文的内部bena工厂。所有bean定义都将被加载,
* 但尚未实例化任何bean。这允许在某些ApplicationContext实现中注册特殊的
* BeanPostProcessor</p>
* @param beanFactory the bean factory used by the application context
* - 应用程序上下文使用的bean工厂
*/
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* <p>实例化并调用所有注册BeanFactoryPostProcess bean,并遵从显式顺序(如果给定的话)</p>
* <p>Must be called before singleton instantiation.
* <p>必须在单例实例化之前调用</p>
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//回调 BeanFactoryPostPorcessors 和 beanFactory的所有BeanFactoryPostProcessor对象的回调方法
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)
// 检测LoadTimeWeaver并准备编织(如果在此期间发现)
// (e.g. 通过 ConfigurationClassPostProcessor注册@Bean方法)
//如果bean工厂没有设置临时类加载器 且 'loadTimeWeaver' 不存在于bean工厂中
// 下面的代码其实跟prepareBeanFactory方法的标记1的代码一样,应该是因为该方法的上一个步是供给子类重写的钩子方法,
// Spring开发人担心经过上一步的处理后,会导致'loadTimeWeaver'被玩坏了,所有才
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
//LoadTimeWeaverAwareProcessor只是用实现了LoadTimeWeaverAware接口的bean
// 回调LoadTimeWeaverAware.setLoadTimeWeaver(LoadTimeWeaver)方法
// 参考博客:https://blog.csdn.net/weixin_34112208/article/details/89750308
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
//ContextTypeMatchClassLoader:该类加载器破坏了双亲委派机制,除指定排除类外,
// 对每个调用loadClass的类,都会新建一个ContextOverridingClassLoader类加载器进行
// 加载,并对每个类的字节缓存起来,以便在父类ClassLoader中拾取 最近加载的类型
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
/**
* Instantiate and register all BeanPostProcessor beans,
* respecting explicit order if given.
* <p>实例化和注册所有 BeanPostProcessor 类型的Bean对象,如果给定的话,遵循显示顺序</p>
* <p>Must be called before any instantiation of application beans.
* <p>必须在应用程序Bean的任何实例化之前调用</p>
*/
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//注册 BeanPostProcessors 到 beanFactory 中
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
/**
* <p>从当前BeanFactory中获取名为 'messageSource' 的 MessageSource 类型的Bean对象,如果没有找到,就创建
* 一个 DelegatingMessageSource 对象作为该上下文的 messageSource 属性值,并将该上下文的 messageSource 注册到
* 该上下文的BeanFactory中。</p>
* <p>默认对该上下文的messageSource设置父级messageSource,父级messageSource为父级上下文的messageSoure属性对象
* 或者父级上下文本身</p>
* Initialize the MessageSource.
* Use parent's if none defined in this context.
* <p>初始化 MessageSource.</p>
* <p>如果在此上下文中没有定义,则使用父级的</p>
*/
protected void initMessageSource() {
//MessageSource:用于解析消息的策略界面,支持此类消息参数化和国际化
//获取当前上下文的BeanFactory对象
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//如果本地BeanFactory包含messageSource的bean,忽略父工厂
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
//从beanFactory中获取名为 'messageSource' 的 MessageSouce 类型的Bean对象
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
// 使 MessageSource 知道 父 MessageSouce
// HierarchicalMessageSource:MessageSource 的子接口,由能分层解析消息的对象实现
// 如果 parent 不为 null && messageSource 是 HierarchicalMessageSource 对象
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
//强转 messageSource 为 HierarchicalMessageSource 对象
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
//获取 hms 的 MessageSource 的父级 MessageSource 对象
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
// 如果还没有注册 父级 MessageSource,只能将父级上下文设置父级 MessageSource
// 获取父级上下文的 MessageSource 对象,将其设置 hms 的 父级 MessagoueSource 对象
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
//如果当前跟踪日志级别
if (logger.isTraceEnabled()) {
// 使用 MessageSource [messageSource]
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {//没有在beanFactory中找到'messageSource'Bean对象时
// Use empty MessageSource to be able to accept getMessage calls.
// 使用 空的 MessageSource 来能够接收 getMessage 调用
DelegatingMessageSource dms = new DelegatingMessageSource();
// 获取父级上下文的 MessageSource 对象,将其设置 hms 的 父级 MessagoueSource 对象
dms.setParentMessageSource(getInternalParentMessageSource());
//设置当前上下文的 messageSource 为 dms
this.messageSource = dms;
//将'messageSource'与 messageSource 注册到 beanFactory 中
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
//如果当前是跟踪日志级别
if (logger.isTraceEnabled()) {
//没有名为'messageSource'的对象,使用 messageSource
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
}
/**
* <p>从beanFactory中获取名为 'applicationEventMulticaster' 的 ApplicationEventMulticaster 类型的Bean对象,引用到
* 该上下文的 applicationEventMulticaster 属性,如果获取不到,就新建一个 SimpleApplicationEventMulticaster 实例 引用
* 到 上下文的 applicationEventMulticaster 属性 中</p>
* Initialize the ApplicationEventMulticaster.
* <p>初始化ApplicationEventMulticaster</p>
* Uses SimpleApplicationEventMulticaster if none defined in the context.
* <p>如果上下文中没有定义,则使用SimpleApplicatioonEventMulticaster</p>
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
protected void initApplicationEventMulticaster() {
//获取当前上下文的BeanFactory对象
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//如果本地BeanFactory包含 applicationEventMulticaster 的bean,忽略父工厂
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
//从beanFactory中获取名为 'applicationEventMulticaster' 的 ApplicationEventMulticaster 类型的Bean对象
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
//如果当前是跟踪日志级别
if (logger.isTraceEnabled()) {
//跟踪日志:使用 ApplicationEventMulticaster [applicationEventMulticaster]
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {//本地BeanFactory没有applicationEventMulticaster的bean对象时
//SimpleApplicationEventMulticaster:简单实现的 ApplicationEventMulticaster 接口;将所有事件多播给所有注册的监听
// 器,让监听器忽略它们不感兴趣的事件。监听器通常 会对传入的事件对象执行相应的 instanceof 检查
//新建一个 SimpleApplicationEventMulticaster 对象
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
//将 applicationEventMulticaster 与 'applicationEventMulticaster' 注册到 beanFactory 中
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
//如果当前是跟踪日志级别
if (logger.isTraceEnabled()) {
没有名为'applicationEventMulticaster'的对象,使用 applicationEventMulticaster
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}
/**
* <p><p>初始化 LifecycleProcessor.如果上下文中找到 'lifecycleProcessor' 的 LifecycleProcessor Bean对象,则使用
* DefaultLifecycleProcessor </p></p>
* Initialize the LifecycleProcessor.
* Uses DefaultLifecycleProcessor if none defined in the context.
* <p>初始化 LifecycleProcessor.如果上下文中没有定义,则使用 DefaultLifecycleProcessor </p>
* @see org.springframework.context.support.DefaultLifecycleProcessor
*/
protected void initLifecycleProcessor() {
//获取当前上下文的BeanFactory对象
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//如果 beanFactory 包含 'lifecycleProcessor' 的bean,忽略父工厂
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
//让当前上下文 引用 从beanFactory中获取名为 'lifecycleProcessor' 的 LifecycleProcessor 类型的Bean对象
this.lifecycleProcessor =
beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
//如果当前日志级级别是跟踪
if (logger.isTraceEnabled()) {
//打印跟踪日志:使用 LifecycleProcessor [lifecycleProcessor]
logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
}
}
else {
//创建一个 DefaultLifecycleProcessor 实例
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
//为Bean实例提供所属工厂的回调函数
defaultProcessor.setBeanFactory(beanFactory);
//让当前上下文 引用 defaultProcessor
this.lifecycleProcessor = defaultProcessor;
//将 'lifecycleProcessor' 与 lifecycleProcessor 注册到 beanFactory 中
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
//如果当前日志级级别是跟踪
if (logger.isTraceEnabled()) {
// 没有 'lifecycleProcessor' 的Bean对象,使用 [lifecycleProcessor类名]
logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
}
}
}
/**
* Template method which can be overridden to add context-specific refresh work.
* Called on initialization of special beans, before instantiation of singletons.
* <p>模板方法,可以重写该方法以添加特定上下文的刷新工作。在实例化单例对象之前,对特殊Bean进行
* 初始化时调用。</p>
* <p>This implementation is empty.
* <p>这个实现时空的。</p>
* @throws BeansException in case of errors -- 以防出现错误
* @see #refresh()
*/
protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
// 对于子类:默认不做任何事情
}
/**
* <p>注册静态指定的监听器和beanFactory内的监听器Bean对象【不会导致监听器Bean对象实例化,仅记录其Bean名】到当前上下文
* 的多播器,然后发布在多播程序设置之前发布的ApplicationEvent集到各个监听器中</p>
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans.
* <p>添加将 ApplicationListener 实现为 监听器 的Bean。不会影响其他 监听器,可以在不使用
* Bean 的情况下添加其他监听器</p>
*/
protected void registerListeners() {
// Register statically specified listeners first.
// 首先注册静态指定的监听器
//遍历 静态指定的 applicationListener 列表
for (ApplicationListener<?> listener : getApplicationListeners()) {
//获取上下文使用的内部 ApplicationEventMulticater,往里面添加 listener
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
// 不要这里初始化FactoryBean:我们需要保持所有常规bean未初始化,以便让BeanPostProcessor应用它们
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
// 遍历listenerBeanNames
for (String listenerBeanName : listenerBeanNames) {
//获取上下文使用的内部 ApplicationEventMulticater,往里面添加一个监听器bean来通知所有事件
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
// 发布早期的应用事件,现在我们终于有了一个多播器
//在多播程序设置之前发布的ApplicationEvent集
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
//将earlyApplicationEvents设置为null,因为要保证一个事件只会多播一次。
this.earlyApplicationEvents = null;
//如果 earlyEventsToProcess 不为 null
if (earlyEventsToProcess != null) {
//遍历 earlyEventsToProcess
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
//获取上下文使用的内部 ApplicationEventMulticater,多播earlyEvent到适当的监听器
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
/**
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
* <p>完成这个上下文BeanFactory的初始化,初始化所有剩余的 单例Bean对象</p>
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
// 为此上下文初始化转换服务
// 该beanFactory包含'conversionService'的BeanDefinition对象或外部注册的singleton实例 &&
// 如果在beanFactory中 'conversionService' 与 ConversionService.class 匹配
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
//从beanFactory中获取名为 'conversionService' 的 ConversionService 类型的Bean对象 作为 beanFactory的转换属性值
// 服务,也作为JavaBeans PropertyEditor的替代方案
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.
// 如果以前没有BeanPostProcessor(比如 PropertyPlaceholderConfigurer Bean)注册过任何Bean,
// 那么注册一个默认的内嵌值解析器:此时,主要是为了解析注释属性值
// 如果当前beanFactory没有字符串解析器,默认是有一个 PropertyPlaceHolderConfigurer 解析器的
if (!beanFactory.hasEmbeddedValueResolver()) {
//新建一个StringValueResolver对象添加字符串解析器
beanFactory.addEmbeddedValueResolver(strVal ->
//获取当前环境对象,在strVal中解析${...}占位符,用getProperty解析的相应属性值 替换它们。
// 带有无默认值的不可解析的占位符将被忽略通过原样传递。
getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
// 尽早初始化 LoadTimeWeaverAware Bean,以便尽早注册它们的转换器
//获取与BeanPostProcessor.class(包括子类)匹配的bean名称,如果是FactoryBeans会根据beanDefinition 或getObjectType的值判断
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
//遍历weaverAwareNames
for (String weaverAwareName : weaverAwareNames) {
//获取在BeanFactory中weaverAwareName对应的Bean对象
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
// 停止使用临时类加载器进行类型匹配
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
// 允许缓存所有BeanDefinition元数据,而不期望进一步的更改
//冻结所有beanDefinition,表示不再进一步修改或后处理已注册的BeanDefinition,这允许工厂积极地缓存bean定义元数据
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
// 实例化所有剩余的(非延迟初始化)单例
//确保所有非延迟初始化单例化都已实例化,同时也要考虑FactoryBean。
beanFactory.preInstantiateSingletons();
}
/**
* <p>完成刷新:
* <ol>
* <li> 清空在资源加载器中的所有资源缓存</li>
* <li> 初始化 LifecycleProcessor.如果上下文中找到 'lifecycleProcessor' 的 LifecycleProcessor Bean对象,
* 则使用 DefaultLifecycleProcessor</li>
* <li> 将刷新传播到生命周期处理器 </li>
* <li> 新建 ContextRefreshedEvent 事件对象,将其发布到所有监听器。 </li>
* <li> 注册 当前上下文 到 LiveBeansView,以支持 JMX 服务</li>
* </ol>
* </p>
* Finish the refresh of this context, invoking the LifecycleProcessor's
* onRefresh() method and publishing the
* {@link org.springframework.context.event.ContextRefreshedEvent}.
* <p>调用 LifecycleProcessor 的 onRefresh() 方法并发布 ContextRefreshedEvent ,完成上下
* 问刷新</p>
*/
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
// 清楚上下文级别的资源缓存(如扫描的ASM元数据)
// 清空在资源加载器中的所有资源缓存
clearResourceCaches();
// Initialize lifecycle processor for this context.
// 为这个上下文初始化生命周期处理器
// 初始化 LifecycleProcessor.如果上下文中找到 'lifecycleProcessor' 的 LifecycleProcessor Bean对象,
// 则使用 DefaultLifecycleProcessor
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
// 首先将刷新传播到生命周期处理器
// 上下文刷新的通知,例如自动启动的组件
getLifecycleProcessor().onRefresh();
// Publish the final event.
// 发布最终事件
// 新建 ContextRefreshedEvent 事件对象,将其发布到所有监听器。
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
// 参与 LiveBeansView MBean,如果是活动的
// LiveBeansView:Sping 用于支持 JMX 服务的类,详情请参考:https://www.jianshu.com/p/fa4e88f95631
// 注册 当前上下文 到 LiveBeansView,以支持 JMX 服务
LiveBeansView.registerApplicationContext(this);
}
/**
* Cancel this context's refresh attempt, resetting the {@code active} flag
* after an exception got thrown.
* <p> 取消 此上下文的刷新尝试,在抛出异常后 重置 active 标志</p>
* @param ex the exception that led to the cancellation
* -- 导致取消的异常
*/
protected void cancelRefresh(BeansException ex) {
this.active.set(false);
}
/**
* <p>删除ReflectionUtils,AnnotationUtils,ResolvableType的缓存,清除当前的类加载器的自省缓存,删除该类加载器下
* 所有类的自省结果,并从接受列表中删除类加载器(及其子类)</p>
* Reset Spring's common reflection metadata caches, in particular the
* {@link ReflectionUtils}, {@link AnnotationUtils}, {@link ResolvableType}
* and {@link CachedIntrospectionResults} caches.
* <p>在 Spring 的核心中重置常见的自省缓存,因为我们可能不再需要单例bean的元数据了</p>
* @since 4.2
* @see ReflectionUtils#clearCache()
* @see AnnotationUtils#clearCache()
* @see ResolvableType#clearCache()
* @see CachedIntrospectionResults#clearClassLoader(ClassLoader)
*/
protected void resetCommonCaches() {
//将ReflectionUtil的DeclaredMethod缓存,declaredFields缓存清空【使用ReflectionUtil来解析出类的DeclaredMethod,declaredFields都会加入到该缓存中】
ReflectionUtils.clearCache();
//清除内部注解元数据缓存
AnnotationUtils.clearCache();
//清除内部的ResolvableType缓存和SerializableTypeWrapper缓存
ResolvableType.clearCache();
//CachedIntrospectionResults:为Java类缓存JavaBeans PropertyDescriptor信息的内部类。不打算由应用程序代码直接 使用
//清除当前的类加载器的自省缓存,删除该类加载器下所有类的自省结果,并从接受列表中删除类加载器(及其子类)
CachedIntrospectionResults.clearClassLoader(getClassLoader());
}
/**
* Register a shutdown hook {@linkplain Thread#getName() named}
* {@code SpringContextShutdownHook} with the JVM runtime, closing this
* context on JVM shutdown unless it has already been closed at that time.
* <p>Delegates to {@code doClose()} for the actual closing procedure.
* @see Runtime#addShutdownHook
* @see ConfigurableApplicationContext#SHUTDOWN_HOOK_THREAD_NAME
* @see #close()
* @see #doClose()
*/
@Override
public void registerShutdownHook() {
if (this.shutdownHook == null) {
// No shutdown hook registered yet.
this.shutdownHook = new Thread(SHUTDOWN_HOOK_THREAD_NAME) {
@Override
public void run() {
synchronized (startupShutdownMonitor) {
doClose();
}
}
};
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
}
}
/**
* Callback for destruction of this instance, originally attached
* to a {@code DisposableBean} implementation (not anymore in 5.0).
* <p>The {@link #close()} method is the native way to shut down
* an ApplicationContext, which this method simply delegates to.
* @deprecated as of Spring Framework 5.0, in favor of {@link #close()}
*/
@Deprecated
public void destroy() {
close();
}
/**
* Close this application context, destroying all beans in its bean factory.
* <p>Delegates to {@code doClose()} for the actual closing procedure.
* Also removes a JVM shutdown hook, if registered, as it's not needed anymore.
* @see #doClose()
* @see #registerShutdownHook()
*/
@Override
public void close() {
synchronized (this.startupShutdownMonitor) {
doClose();
// If we registered a JVM shutdown hook, we don't need it anymore now:
// We've already explicitly closed the context.
if (this.shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
}
catch (IllegalStateException ex) {
// ignore - VM is already shutting down
}
}
}
}
/**
* Actually performs context closing: publishes a ContextClosedEvent and
* destroys the singletons in the bean factory of this application context.
* <p>Called by both {@code close()} and a JVM shutdown hook, if any.
* @see org.springframework.context.event.ContextClosedEvent
* @see #destroyBeans()
* @see #close()
* @see #registerShutdownHook()
*/
protected void doClose() {
// Check whether an actual close attempt is necessary...
if (this.active.get() && this.closed.compareAndSet(false, true)) {
if (logger.isDebugEnabled()) {
logger.debug("Closing " + this);
}
LiveBeansView.unregisterApplicationContext(this);
try {
// Publish shutdown event.
publishEvent(new ContextClosedEvent(this));
}
catch (Throwable ex) {
logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);
}
// Stop all Lifecycle beans, to avoid delays during individual destruction.
if (this.lifecycleProcessor != null) {
try {
this.lifecycleProcessor.onClose();
}
catch (Throwable ex) {
logger.warn("Exception thrown from LifecycleProcessor on context close", ex);
}
}
// Destroy all cached singletons in the context's BeanFactory.
destroyBeans();
// Close the state of this context itself.
closeBeanFactory();
// Let subclasses do some final clean-up if they wish...
onClose();
// Reset local application listeners to pre-refresh state.
if (this.earlyApplicationListeners != null) {
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Switch to inactive.
this.active.set(false);
}
}
/**
* Template method for destroying all beans that this context manages.
* The default implementation destroy all cached singletons in this context,
* invoking {@code DisposableBean.destroy()} and/or the specified
* "destroy-method".
* <p>用于销毁此上下文管理的所有bean的模板方法。
* 默认实现此上下文中销毁所有缓存的单例,调用{@code DisposableBean.destroy()}和
* 或指定的'destory-method'</p>
*
* <p>Can be overridden to add context-specific bean destruction steps
* right before or right after standard singleton destruction,
* while the context's BeanFactory is still active.
* <p>可以被覆盖以添加上下文特定的bean销毁步骤在标准单例销毁之前或之后,在上下文
* 的BeanFactory仍处于活动状态时</p>
*
* @see #getBeanFactory()
* @see org.springframework.beans.factory.config.ConfigurableBeanFactory#destroySingletons()
*/
protected void destroyBeans() {
//销毁在工厂中的所有单例bean,包括已注册为一次性的内部bean。在工厂关闭时调用。
getBeanFactory().destroySingletons();
}
/**
* Template method which can be overridden to add context-specific shutdown work.
* The default implementation is empty.
* <p>Called at the end of {@link #doClose}'s shutdown procedure, after
* this context's BeanFactory has been closed. If custom shutdown logic
* needs to execute while the BeanFactory is still active, override
* the {@link #destroyBeans()} method instead.
*/
protected void onClose() {
// For subclasses: do nothing by default.
}
@Override
public boolean isActive() {
return this.active.get();
}
/**
* <p>如果此上下文没有处于活动状态,就抛出异常</p>
* Assert that this context's BeanFactory is currently active,
* throwing an {@link IllegalStateException} if it isn't.
* <p>断言 此上下文的BeanFactory当前是活动的,如果不是,则抛出 IllegalStateException</p>
* <p>Invoked by all {@link BeanFactory} delegation methods that depend
* on an active context, i.e. in particular all bean accessor methods.
* <p>由依赖于活动上下文的所有BeanFactory的所有BeanFactory委托方法调用,特别是所有Bean访问器方法</p>
* <p>The default implementation checks the {@link #isActive() 'active'} status
* of this context overall. May be overridden for more specific checks, or for a
* no-op if {@link #getBeanFactory()} itself throws an exception in such a case.
* <p>默认实现检查上下文的'active'状态。对应更具体的检查,或者对应无操作(如果getBeanfactory())本身
* 再这种情况下抛出异常),可能会被覆盖</p>
*/
protected void assertBeanFactoryActive() {
//如果 此上下文没有处于活动状态
if (!this.active.get()) {
//如果此上下文处于关闭状态
if (this.closed.get()) {
//抛出 非法状态异常:displayName 已经关闭
throw new IllegalStateException(getDisplayName() + " has been closed already");
}
else {
//抛出 非法状态异常:displayName 还没有刷新完
throw new IllegalStateException(getDisplayName() + " has not been refreshed yet");
}
}
}
//---------------------------------------------------------------------
// Implementation of BeanFactory interface
//---------------------------------------------------------------------
@Override
public Object getBean(String name) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name);
}
@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name, requiredType);
}
@Override
public Object getBean(String name, Object... args) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name, args);
}
@Override
public <T> T getBean(Class<T> requiredType) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(requiredType);
}
@Override
public <T> T getBean(Class<T> requiredType, Object... args) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(requiredType, args);
}
@Override
public <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType) {
assertBeanFactoryActive();
return getBeanFactory().getBeanProvider(requiredType);
}
@Override
public <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType) {
assertBeanFactoryActive();
return getBeanFactory().getBeanProvider(requiredType);
}
@Override
public boolean containsBean(String name) {
return getBeanFactory().containsBean(name);
}
@Override
public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().isSingleton(name);
}
@Override
public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().isPrototype(name);
}
@Override
public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().isTypeMatch(name, typeToMatch);
}
@Override
public boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException {
//如果此上下文没有处于活动状态,就抛出异常
assertBeanFactoryActive();
//检查具有给定名称的bean是否与指定的类型匹配
return getBeanFactory().isTypeMatch(name, typeToMatch);
}
@Override
@Nullable
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().getType(name);
}
@Override
@Nullable
public Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().getType(name, allowFactoryBeanInit);
}
@Override
public String[] getAliases(String name) {
return getBeanFactory().getAliases(name);
}
//---------------------------------------------------------------------
// Implementation of ListableBeanFactory interface
//---------------------------------------------------------------------
@Override
public boolean containsBeanDefinition(String beanName) {
return getBeanFactory().containsBeanDefinition(beanName);
}
@Override
public int getBeanDefinitionCount() {
return getBeanFactory().getBeanDefinitionCount();
}
@Override
public String[] getBeanDefinitionNames() {
return getBeanFactory().getBeanDefinitionNames();
}
@Override
public String[] getBeanNamesForType(ResolvableType type) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForType(type);
}
@Override
public String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
}
@Override
public String[] getBeanNamesForType(@Nullable Class<?> type) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForType(type);
}
@Override
public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
}
@Override
public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBeansOfType(type);
}
@Override
public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBeansOfType(type, includeNonSingletons, allowEagerInit);
}
@Override
public String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) {
assertBeanFactoryActive();
return getBeanFactory().getBeanNamesForAnnotation(annotationType);
}
@Override
public Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType)
throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBeansWithAnnotation(annotationType);
}
@Override
@Nullable
public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().findAnnotationOnBean(beanName, annotationType);
}
//---------------------------------------------------------------------
// Implementation of HierarchicalBeanFactory interface
//---------------------------------------------------------------------
@Override
@Nullable
public BeanFactory getParentBeanFactory() {
return getParent();
}
@Override
public boolean containsLocalBean(String name) {
return getBeanFactory().containsLocalBean(name);
}
/**
* Return the internal bean factory of the parent context if it implements
* ConfigurableApplicationContext; else, return the parent context itself.
* <p>如果父级bean工厂实现了ConfigurableApplicationContext接口,则返回父上下文的
* 内部bean工厂。否则,返回父上下文本身</p>
* @see org.springframework.context.ConfigurableApplicationContext#getBeanFactory
*/
@Nullable
protected BeanFactory getInternalParentBeanFactory() {
return (getParent() instanceof ConfigurableApplicationContext ?
((ConfigurableApplicationContext) getParent()).getBeanFactory() : getParent());
}
//---------------------------------------------------------------------
// Implementation of MessageSource interface
//---------------------------------------------------------------------
@Override
public String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale) {
return getMessageSource().getMessage(code, args, defaultMessage, locale);
}
@Override
public String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException {
return getMessageSource().getMessage(code, args, locale);
}
@Override
public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException {
return getMessageSource().getMessage(resolvable, locale);
}
/**
* Return the internal MessageSource used by the context.
* @return the internal MessageSource (never {@code null})
* @throws IllegalStateException if the context has not been initialized yet
*/
private MessageSource getMessageSource() throws IllegalStateException {
if (this.messageSource == null) {
throw new IllegalStateException("MessageSource not initialized - " +
"call 'refresh' before accessing messages via the context: " + this);
}
return this.messageSource;
}
/**
* Return the internal message source of the parent context if it is an
* AbstractApplicationContext too; else, return the parent context itself.
* <p>如果父上下文也是 AbstractApplicationContext ,则返回父上下文的内部消息源;
* 否则,返回父上下文本身</p>
*/
@Nullable
protected MessageSource getInternalParentMessageSource() {
//如果父级上下文是AbstractApplicationContext对象,就返回其messageSource;否则直接返回父级上下文
return (getParent() instanceof AbstractApplicationContext ?
((AbstractApplicationContext) getParent()).messageSource : getParent());
}
//---------------------------------------------------------------------
// Implementation of ResourcePatternResolver interface
//---------------------------------------------------------------------
@Override
public Resource[] getResources(String locationPattern) throws IOException {
return this.resourcePatternResolver.getResources(locationPattern);
}
//---------------------------------------------------------------------
// Implementation of Lifecycle interface
//---------------------------------------------------------------------
@Override
public void start() {
getLifecycleProcessor().start();
publishEvent(new ContextStartedEvent(this));
}
@Override
public void stop() {
getLifecycleProcessor().stop();
publishEvent(new ContextStoppedEvent(this));
}
@Override
public boolean isRunning() {
return (this.lifecycleProcessor != null && this.lifecycleProcessor.isRunning());
}
//---------------------------------------------------------------------
// Abstract methods that must be implemented by subclasses
//---------------------------------------------------------------------
/**
* Subclasses must implement this method to perform the actual configuration load.
* The method is invoked by {@link #refresh()} before any other initialization work.
* <p>子类必须实现此方法才能执行实际的配置加载。在进行任何其他舒适化工作之前,该方法由
* {@link #refresh()}调用。</p>
*
* <p>A subclass will either create a new bean factory and hold a reference to it,
* or return a single BeanFactory instance that it holds. In the latter case, it will
* usually throw an IllegalStateException if refreshing the context more than once.
* <p>子类创建一个新的bean工厂并保留对其的引用,或者返回它持有的单个BeanFactory实例。在
* 后一种情况下,如果多次属性上下文,通常会抛出IllegalStateException</p>
*
* @throws BeansException if initialization of the bean factory failed
* -- 如果bean工厂初始化失败
* @throws IllegalStateException if already initialized and multiple refresh
* attempts are not supported
* -- 如果已经初始化并且不支持多次刷新尝试
*/
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
/**
* Subclasses must implement this method to release their internal bean factory.
* This method gets invoked by {@link #close()} after all other shutdown work.
* <p>子类必须必须实现此方法才能释放其内部bean工厂。在所有其他关闭工作之后,此方法
* 将由{@link #close()}调用</p>
*
* <p>Should never throw an exception but rather log shutdown failures.
* <p>永远不要抛出异常,应该记录关闭失败</p>
*/
protected abstract void closeBeanFactory();
/**
* <p>获取当前上下文的BeanFactory对象</p>
* Subclasses must return their internal bean factory here. They should implement the
* lookup efficiently, so that it can be called repeatedly without a performance penalty.
* <p>子类必须在此返回其内部bean工厂。他们应该有效地实现查找,以便可以重复调用它而不
* 影响性能</p>
*
* <p>Note: Subclasses should check whether the context is still active before
* returning the internal bean factory. The internal factory should generally be
* considered unavailable once the context has been closed.
* <p>注意:子类应在返回内部bean工厂之前检验上下文是否仍处于活动状态。一旦关闭上下
* 文,通常应将内部工厂视为不可用,</p>
*
* @return this application context's internal bean factory (never {@code null})
* --此应用程序上下文的内部bean工厂(永远不为{@code null})
* @throws IllegalStateException if the context does not hold an internal bean factory yet
* (usually if {@link #refresh()} has never been called) or if the context has been
* closed already
* -- 如果上下文尚未拥有内部bean工厂(通常是从未调用过{@link #refresh()}),或上下文已经关闭
* @see #refreshBeanFactory()
* @see #closeBeanFactory()
*/
@Override
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
/**
* Return information about this context.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getDisplayName());
sb.append(", started on ").append(new Date(getStartupDate()));
ApplicationContext parent = getParent();
if (parent != null) {
sb.append(", parent: ").append(parent.getDisplayName());
}
return sb.toString();
}
}