package org.springframework.context.support;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.CachedIntrospectionResults;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryInitializer;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.support.ResourceEditorRegistrar;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ApplicationStartupAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.HierarchicalMessageSource;
import org.springframework.context.LifecycleProcessor;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.expression.StandardBeanExpressionResolver;
import org.springframework.context.weaving.LoadTimeWeaverAware;
import org.springframework.context.weaving.LoadTimeWeaverAwareProcessor;
import org.springframework.core.NativeDetector;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.metrics.ApplicationStartup;
import org.springframework.core.metrics.StartupStep;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
/**
* {@link org.springframework.context.ApplicationContext}接口的抽象实现。
* 不强制要求用于配置的存储类型;简单地实现了通用上下文功能。使用模板方法设计模式,需要具体的子类来实现抽象方法。
*
* <p>与普通的BeanFactory不同,ApplicationContext应该检测其内部bean工厂中定义的特殊bean:
* 因此,这个类会自动注册在上下文中被定义的下列bean定义。
* {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor BeanFactoryPostProcessors},
* {@link org.springframework.beans.factory.config.BeanPostProcessor BeanPostProcessors},
* 和 {@link org.springframework.context.ApplicationListener ApplicationListeners}
*
* <p>{@link org.springframework.context.MessageSource}也可以作为bean在上下文中提供,名称为“MessageSource”;
* 否则,消息解析将委托给父上下文。此外,应用程序事件的多播器可以在上下文中作为类型为
* {@link org.springframework.context.event.applicationEventMulticaster}的“applicationEventMulticaster”bean提供;
* 否则,将使用类型为{@link org.springframework.context.event.SimpleApplicationEventMulticaster}的默认多播器。
*
* <p>通过扩展{@link org.springframework.core.io.DefaultResourceLoader}实现资源加载。
* 因此,将非URL资源路径视为类路径资源 (支持包含包路径的完整类路径资源名称,例如“mypackage/myresource.dat”),
* 除非在子类中重写了{@link#getResourceByPath}方法。
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Mark Fisher
* @author Stephane Nicoll
* @author Sam Brannen
* @author Sebastien Deleuze
* @author Brian Clozel
* @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 {
/**
* 上下文中{@link MessageSource}bean的名称。如果没有提供,则将消息解析委托给父级。
* @see org.springframework.context.MessageSource
* @see org.springframework.context.support.ResourceBundleMessageSource
* @see org.springframework.context.support.ReloadableResourceBundleMessageSource
* @see #getMessage(MessageSourceResolvable, Locale)
*/
public static final String MESSAGE_SOURCE_BEAN_NAME = "messageSource";
/**
* 上下文中{@link ApplicationEventMulticaster}bean的名称。如果没有提供,则使用{@link SimpleApplicationEventMulticaster}。
* @see org.springframework.context.event.ApplicationEventMulticaster
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
* @see #publishEvent(ApplicationEvent)
* @see #addApplicationListener(ApplicationListener)
*/
public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
/**
* 上下文中{@link LifecycleProcessor}bean的名称。如果没有提供,则使用{@link DefaultLifecycleProcessor}。
* @since 3.0
* @see org.springframework.context.LifecycleProcessor
* @see org.springframework.context.support.DefaultLifecycleProcessor
* @see #start()
* @see #stop()
*/
public static final String LIFECYCLE_PROCESSOR_BEAN_NAME = "lifecycleProcessor";
static {
// 急切地加载ContextClosedEvent类,以避免WebLogic 8.1中应用程序关闭时出现奇怪的类加载器问题。(Reported by Dustin Woods.)
ContextClosedEvent.class.getName();
}
/** 此类使用的Logger。可用于子类。 */
protected final Log logger = LogFactory.getLog(getClass());
/** 此上下文的唯一id(如果有)。 */
private String id = ObjectUtils.identityToString(this);
/** 显示名称。 */
private String displayName = ObjectUtils.identityToString(this);
/** 父上下文 */
@Nullable
private ApplicationContext parent;
/** 此上下文使用的Environment。 */
@Nullable
private ConfigurableEnvironment environment;
/** 应用于refresh方法的BeanFactoryPostProcessors。 */
private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors = new ArrayList<>();
/** 此上下文启动时的系统时间(毫秒)。 */
private long startupDate;
/** 指示此上下文当前是否处于活动(active)状态的标志。 */
private final AtomicBoolean active = new AtomicBoolean();
/** 指示此上下文是否已关闭(closed)的标志。 */
private final AtomicBoolean closed = new AtomicBoolean();
/** Synchronization lock for "refresh" and "close". */
private final Lock startupShutdownLock = new ReentrantLock();
/** Currently active startup/shutdown thread. */
@Nullable
private volatile Thread startupShutdownThread;
/** 如果已注册,则引用JVM shutdown 挂钩。 */
@Nullable
private Thread shutdownHook;
/** 此上下文使用的ResourcePatternResolver。 */
private final ResourcePatternResolver resourcePatternResolver;
/** LifecycleProcessor用于在此上下文中管理bean的生命周期。 */
@Nullable
private LifecycleProcessor lifecycleProcessor;
/** MessageSource 我们将此接口的实现委托给MessageSource。 */
@Nullable
private MessageSource messageSource;
/** 事件发布中使用的辅助类。 */
@Nullable
private ApplicationEventMulticaster applicationEventMulticaster;
/** 应用程序启动指标。 */
private ApplicationStartup applicationStartup = ApplicationStartup.DEFAULT;
/** 静态指定的侦听器。 */
private final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();
/** refresh方法前注册的本地侦听器。 */
@Nullable
private Set<ApplicationListener<?>> earlyApplicationListeners;
/** 在多播器设置之前发布的ApplicationEvents。 */
@Nullable
private Set<ApplicationEvent> earlyApplicationEvents;
/**
* 创建一个没有父上下文的新AbstractApplicationContext。
*/
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
/**
* 使用给定的父上下文创建新的AbstractApplicationContext。
* @param parent 父上下文
*/
public AbstractApplicationContext(@Nullable ApplicationContext parent) {
this();
setParent(parent);
}
//---------------------------------------------------------------------
// ApplicationContext接口的实现
//---------------------------------------------------------------------
/**
* 设置此应用程序上下文的唯一 ID。
* <p>默认值是上下文实例的对象 ID,或者上下文 bean 的名称(如果上下文本身定义为 bean)。
* @param id 上下文的唯一ID
*/
@Override
public void setId(String id) {
this.id = id;
}
@Override
public String getId() {
return this.id;
}
@Override
public String getApplicationName() {
return "";
}
/**
* 为此上下文设置一个友好的名称。 通常在具体上下文实现的初始化期间完成。
* <p>默认值是上下文实例的对象 ID。
*/
public void setDisplayName(String displayName) {
Assert.hasLength(displayName, "Display name must not be empty");
this.displayName = displayName;
}
/**
* 返回此上下文的友好名称。
* @return 此上下文的显示名称(绝不是 {@code null})
*/
@Override
public String getDisplayName() {
return this.displayName;
}
/**
* 返回父上下文,如果没有父上下文,则返回 {@code null} (即,此上下文是上下文层次结构的根)。
*/
@Override
@Nullable
public ApplicationContext getParent() {
return this.parent;
}
/**
* 为此应用程序上下文设置{@code Environment}。
* <p>默认值由{@link #createEnvironment()}确定。
* 使用此方法替换默认值是一种选择,但也应考虑通过 {@link #getEnvironment()} 进行配置。
* 无论哪种情况,此类修改都应在{@link #refresh()}之前执行。
* @see org.springframework.context.support.AbstractApplicationContext#createEnvironment
*/
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
this.environment = environment;
}
/**
* 以可配置的形式返回此应用程序上下文的 {@code Environment},以便进一步自定义。
* <p>如果未指定,将通过 {@link #createEnvironment()} 初始化默认环境。
*/
@Override
public ConfigurableEnvironment getEnvironment() {
if (this.environment == null) {
this.environment = createEnvironment();
}
return this.environment;
}
/**
* 创建并返回一个新的{@link StandardEnvironment}。
* <p>子类可以重写此方法以提供自定义的{@link ConfigurableEnvironment}实现。
*/
protected ConfigurableEnvironment createEnvironment() {
return new StandardEnvironment();
}
/**
* 返回此上下文的内部 bean 工厂作为 AutowireCapableBeanFactory(如果已经可用)。
* @see #getBeanFactory()
*/
@Override
public AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException {
return getBeanFactory();
}
/**
* 返回首次加载此上下文时的时间戳(毫秒)。
*/
@Override
public long getStartupDate() {
return this.startupDate;
}
/**
* 将给定事件发布给所有侦听器。
* <p>注意:侦听器在 MessageSource 之后初始化,以便能够在侦听器实现中访问它。
* 因此,MessageSource 实现无法发布事件。
* @param event 要发布的事件(可能是特定于应用程序的事件或标准框架事件)
*/
@Override
public void publishEvent(ApplicationEvent event) {
publishEvent(event, null);
}
/**
* 将给定事件发布给所有侦听器。
* <p>注意:侦听器在 MessageSource 之后初始化,以便能够在侦听器实现中访问它。
* 因此,MessageSource 实现无法发布事件。
* @param event要发布的事件(可以是 {@link ApplicationEvent}
* 或要转换为 {@link PayloadApplicationEvent} 的有效负载对象)
*/
@Override
public void publishEvent(Object event) {
publishEvent(event, null);
}
/**
* 将给定事件发布给所有侦听器。
* <p>这是所有其他 {@code publishEvent} 方法引用的内部委托。
* 它并不意味着直接调用,而是充当层次结构中应用程序上下文之间的传播机制,
* 可能会在子类中重写以实现自定义传播安排。
* @param event 要发布的事件(可以是 {@link ApplicationEvent}
* 或要转换为 {@link PayloadApplicationEvent} 的有效负载对象)
* @param typeHint 解析的事件类型(如果已知)。
* 此方法的实现还允许将有效负载对象转换为 {@link PayloadApplicationEvent} 的有效负载类型提示。
* 然而,对于这种情况,推荐的方法是通过 {@link PayloadApplicationEvent#PayloadApplicationEvent(Object, Object, ResolvableType)}
* 构造一个实际的事件对象。
* @since 4.2
* @see ApplicationEventMulticaster#multicastEvent(ApplicationEvent, ResolvableType)
*/
protected void publishEvent(Object event, @Nullable ResolvableType typeHint) {
Assert.notNull(event, "Event must not be null");
ResolvableType eventType = null;
// 如有必要,将事件装饰为 ApplicationEvent
ApplicationEvent applicationEvent;
if (event instanceof ApplicationEvent applEvent) {
applicationEvent = applEvent;
eventType = typeHint;
}
else {
ResolvableType payloadType = null;
if (typeHint != null && ApplicationEvent.class.isAssignableFrom(typeHint.toClass())) {
eventType = typeHint;
}
else {
payloadType = typeHint;
}
applicationEvent = new PayloadApplicationEvent<>(this, event, payloadType);
}
// 仅确定一次事件类型(对于多播和父发布)
if (eventType == null) {
eventType = ResolvableType.forInstance(applicationEvent);
if (typeHint == null) {
typeHint = eventType;
}
}
// 如果可能的话,立即进行多播 - 或者在多播器初始化后延迟进行
if (this.earlyApplicationEvents != null) {
this.earlyApplicationEvents.add(applicationEvent);
}
else if (this.applicationEventMulticaster != null) {
this.applicationEventMulticaster.multicastEvent(applicationEvent, eventType);
}
// 也通过父上下文发布事件。。。
if (this.parent != null) {
if (this.parent instanceof AbstractApplicationContext abstractApplicationContext) {
abstractApplicationContext.publishEvent(event, typeHint);
}
else {
this.parent.publishEvent(event);
}
}
}
/**
* 返回上下文使用的内部ApplicationEventMulticaster。
* @return 内部ApplicationEventMulticaster(绝不是{@code null})
* @throws IllegalStateException 如果上下文尚未初始化
*/
ApplicationEventMulticaster getApplicationEventMulticaster() throws IllegalStateException {
if (this.applicationEventMulticaster == null) {
throw new IllegalStateException("ApplicationEventMulticaster not initialized - " +
"call 'refresh' before multicasting events via the context: " + this);
}
return this.applicationEventMulticaster;
}
@Override
public void setApplicationStartup(ApplicationStartup applicationStartup) {
Assert.notNull(applicationStartup, "ApplicationStartup must not be null");
this.applicationStartup = applicationStartup;
}
@Override
public ApplicationStartup getApplicationStartup() {
return this.applicationStartup;
}
/**
* 返回上下文使用的内部 LifecycleProcessor。
* @return 内部 LifecycleProcessor(绝不是 {@code null})
* @throws IllegalStateException 如果上下文尚未初始化
*/
LifecycleProcessor getLifecycleProcessor() throws IllegalStateException {
if (this.lifecycleProcessor == null) {
throw new IllegalStateException("LifecycleProcessor not initialized - " +
"call 'refresh' before invoking lifecycle methods via the context: " + this);
}
return this.lifecycleProcessor;
}
/**
* 返回 ResourcePatternResolver 用于将位置模式解析为 Resource 实例。
* 默认是一个{@link org.springframework.core.io.support.PathMatchingResourcePatternResolver},
* 支持 Ant 风格的位置模式。
* <p>可以在子类中重写,以实现扩展的解析策略,例如在 Web 环境中。
* <p><b>当需要解析位置模式时不要调用此方法。</b>
* 请改为调用上下文的 {@code getResources} 方法,该方法将委托给 ResourcePatternResolver。
* @return 此上下文的 ResourcePatternResolver
* @see #getResources
* @see org.springframework.core.io.support.PathMatchingResourcePatternResolver
*/
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}
//---------------------------------------------------------------------
// ConfigurableApplicationContext接口的实现
//---------------------------------------------------------------------
/**
* 设置此应用程序上下文的父级。
* <p>如果父级不是 {@code null} 并且其environment是 {@link ConfigurableEnvironment} 的实例,
* 父 {@linkplain ApplicationContext#getEnvironment() environment}
* 与此(子)应用程序上下文环境 {@linkplain ConfigurableEnvironment#merge(ConfigurableEnvironment) 合并}
* @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 configurableEnvironment) {
getEnvironment().merge(configurableEnvironment);
}
}
}
@Override
public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor) {
Assert.notNull(postProcessor, "BeanFactoryPostProcessor must not be null");
this.beanFactoryPostProcessors.add(postProcessor);
}
/**
* 返回将应用于内部 BeanFactory 的 BeanFactoryPostProcessors 列表。
*/
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);
}
@Override
public void removeApplicationListener(ApplicationListener<?> listener) {
Assert.notNull(listener, "ApplicationListener must not be null");
if (this.applicationEventMulticaster != null) {
this.applicationEventMulticaster.removeApplicationListener(listener);
}
this.applicationListeners.remove(listener);
}
/**
* 返回静态指定的 ApplicationListener 的列表。
*/
public Collection<ApplicationListener<?>> getApplicationListeners() {
return this.applicationListeners;
}
@Override
public void refresh() throws BeansException, IllegalStateException {
this.startupShutdownLock.lock();
try {
this.startupShutdownThread = Thread.currentThread();
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// 准备此上下文以供刷新。
prepareRefresh();
// 告诉子类刷新内部bean工厂。
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 准备 bean 工厂以供在此上下文中使用。
prepareBeanFactory(beanFactory);
try {
// 允许在上下文子类中对 bean 工厂进行后处理。
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// 调用在上下文中注册为 bean 的工厂处理器。
invokeBeanFactoryPostProcessors(beanFactory);
// 注册拦截 Bean 创建的 Bean 处理器。
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// 初始化此上下文的消息源。
initMessageSource();
// 为此上下文初始化事件多播器。
initApplicationEventMulticaster();
// 在特定上下文子类中初始化其他特殊 bean。
onRefresh();
// 检查侦听器 bean 并注册它们。
registerListeners();
// 实例化所有剩余的(非惰性初始化)单例。
finishBeanFactoryInitialization(beanFactory);
// 最后一步:发布相应的事件。
finishRefresh();
}
catch (RuntimeException | Error ex ) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// 销毁已经创建的单例以避免悬空资源。
destroyBeans();
// 重置“active”标志。
cancelRefresh(ex);
// 将异常传播给调用者。
throw ex;
}
finally {
contextRefresh.end();
}
}
finally {
this.startupShutdownThread = null;
this.startupShutdownLock.unlock();
}
}
/**
* 准备此上下文以进行刷新、设置其启动日期和活动标志以及执行属性源的任何初始化。
*/
protected void prepareRefresh() {
// 切换到active。
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// 初始化上下文环境中的任何占位符属性源。
initPropertySources();
// 验证所有标记为必需的属性都是可解析的:
// 请参阅 ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties();
// 存储预刷新 ApplicationListeners...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// 将本地应用程序侦听器重置为刷新前状态。
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// 允许收集早期应用程序事件,一旦多播器可用即可发布...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
/**
* <p>将任何存根属性源替换为实际实例。
* @see org.springframework.core.env.PropertySource.StubPropertySource
* @see org.springframework.web.context.support.WebApplicationContextUtils#initServletPropertySources
*/
protected void initPropertySources() {
// 子类实现:默认情况下不执行任何操作。
}
/**
* 告诉子类刷新内部bean工厂。
* @return 新的 BeanFactory 实例
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
/**
* 配置工厂的标准上下文特征,例如上下文的类加载器和后处理器。
* @param beanFactory 要配置的 BeanFactory
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 告诉内部 bean 工厂使用上下文的类加载器等。
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// 使用上下文回调配置 bean 工厂。
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(ApplicationStartupAware.class);
// BeanFactory 接口未在普通工厂中注册为可解析类型。
// MessageSource 已注册(并被发现用于自动装配)为 bean。
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// 注册早期后处理器以检测内部 bean 作为 ApplicationListener。
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// 检测 LoadTimeWeaver 并准备织入(如果找到)。
if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// 设置一个临时ClassLoader用于类型匹配。
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// 注册默认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());
}
}
/**
* 在标准初始化后修改应用程序上下文的内部 bean 工厂。
* 初始定义资源将被加载,但不会运行任何后处理器,并且不会注册任何派生 bean 定义,
* 最重要的是,还没有任何 Bean 被实例化。
* <p>此模板方法允许在某些 AbstractApplicationContext 子类中注册特殊的 BeanPostProcessors 等。
* @param beanFactory 应用程序上下文使用的bean工厂
*/
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
/**
* 实例化并调用所有已注册的 BeanFactoryPostProcessor beans,如果给定的话,请遵守显式顺序。
* <p>必须在单例实例化之前调用。
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// 检测 LoadTimeWeaver 并准备织入(如果同时找到的话)(例如,通过 ConfigurationClassPostProcessor 注册的 @Bean 方法)
if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null &&
beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
/**
* 实例化并注册所有 BeanPostProcessor beans,如果给定的话,请遵守显式顺序。
* <p>必须在应用程序 Bean 的任何实例化之前调用。
*/
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
/**
* 初始化{@link MessageSource}。
* <p>如果在此上下文中未定义,则使用父级的 {@code MessageSource}。
* @see #MESSAGE_SOURCE_BEAN_NAME
*/
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// 使MessageSource意识到父MessageSource。
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource hms &&
hms.getParentMessageSource() == null) {
// 如果尚未注册父 MessageSource,则仅将父上下文设置为父 MessageSource。
hms.setParentMessageSource(getInternalParentMessageSource());
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// 使用空 MessageSource 才能接受 getMessage 调用。
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isTraceEnabled()) {
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
}
/**
* 初始化 {@link ApplicationEventMulticaster} 。
* <p>如果上下文中没有定义,则使用 {@link SimpleApplicationEventMulticaster} 。
* @see #APPLICATION_EVENT_MULTICASTER_BEAN_NAME
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
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);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}
/**
* 初始化 {@link LifecycleProcessor} 。
* <p>如果上下文中没有定义,则使用 {@link DefaultLifecycleProcessor} 。
* @since 3.0
* @see #LIFECYCLE_PROCESSOR_BEAN_NAME
* @see org.springframework.context.support.DefaultLifecycleProcessor
*/
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
this.lifecycleProcessor = beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
if (logger.isTraceEnabled()) {
logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
}
}
else {
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
if (logger.isTraceEnabled()) {
logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
}
}
}
/**
* 可以重写模板方法来添加特定于上下文的刷新工作。在单例实例化之前调用特殊 bean 的初始化。
* Called on initialization of special beans, before instantiation of singletons.
* <p>这个实现是空的。
* @throws BeansException 如果出现错误
* @see #refresh()
*/
protected void onRefresh() throws BeansException {
// 子类实现:默认情况下不执行任何操作。
}
/**
* 添加实现 ApplicationListener 作为侦听器的 bean。
* 不影响其他监听器,无需成为bean即可添加。
*/
protected void registerListeners() {
// 首先注册静态指定的侦听器。
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 不要在这里初始化FactoryBean:我们需要让所有常规bean保持未初始化状态,以便后处理器应用于它们!
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// 现在我们终于有了一个多播器,发布早期的应用程序事件......
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
/**
* 完成此上下文的 bean 工厂的初始化,初始化所有剩余的单例 bean。
*/
@SuppressWarnings("unchecked")
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 为此上下文初始化引导执行器。
if (beanFactory.containsBean(BOOTSTRAP_EXECUTOR_BEAN_NAME) &&
beanFactory.isTypeMatch(BOOTSTRAP_EXECUTOR_BEAN_NAME, Executor.class)) {
beanFactory.setBootstrapExecutor(
beanFactory.getBean(BOOTSTRAP_EXECUTOR_BEAN_NAME, Executor.class));
}
// 为此上下文初始化转换服务。
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));
}
// 如果之前没有注册任何 BeanFactoryPostProcessor(例如 PropertySourcesPlaceholderConfigurer bean),
// 则注册一个默认的嵌入值解析器:此时,主要用于注释属性值中的解析。
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// 尽早调用 BeanFactoryInitializer beans 以便尽早初始化特定的其他 beans。
String[] initializerNames = beanFactory.getBeanNamesForType(BeanFactoryInitializer.class, false, false);
for (String initializerName : initializerNames) {
beanFactory.getBean(initializerName, BeanFactoryInitializer.class).initialize(beanFactory);
}
// 尽早初始化 LoadTimeWeaverAware bean,以便尽早注册其转换器。
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
try {
beanFactory.getBean(weaverAwareName, LoadTimeWeaverAware.class);
}
catch (BeanNotOfRequiredTypeException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to initialize LoadTimeWeaverAware bean '" + weaverAwareName +
"' due to unexpected type mismatch: " + ex.getMessage());
}
}
}
// 停止使用临时类加载器进行类型匹配。
beanFactory.setTempClassLoader(null);
// 允许缓存所有 bean 定义元数据,而不期望进一步更改。
beanFactory.freezeConfiguration();
// 实例化所有剩余的 (non-lazy-init) 单例。
beanFactory.preInstantiateSingletons();
}
/**
* 调用 LifecycleProcessor 的 onRefresh() 方法并发布
* {@link org.springframework.context.event.ContextRefreshedEvent},
* 完成此上下文的刷新。
*/
protected void finishRefresh() {
// 重置 Spring 核心基础设施中的常见内省缓存。
resetCommonCaches();
// 清除上下文级别资源缓存(例如扫描的 ASM 元数据)。
clearResourceCaches();
// 为此上下文初始化生命周期处理器。
initLifecycleProcessor();
// 首先将刷新传播到生命周期处理器。
getLifecycleProcessor().onRefresh();
// 发布最终事件。
publishEvent(new ContextRefreshedEvent(this));
}
/**
* 取消此上下文的刷新尝试,在引发异常后重置 {@code active} 标志。
* @param ex 导致取消的异常
*/
protected void cancelRefresh(Throwable ex) {
this.active.set(false);
// 重置 Spring 核心基础设施中的常见内省缓存。
resetCommonCaches();
}
/**
* 重置 Spring 的常见反射元数据缓存,特别是 {@link ReflectionUtils}、{@link AnnotationUtils}、
* {@link ResolvableType} 和 {@link CachedIntrospectionResults} 缓存。
* @since 4.2
* @see ReflectionUtils#clearCache()
* @see AnnotationUtils#clearCache()
* @see ResolvableType#clearCache()
* @see CachedIntrospectionResults#clearClassLoader(ClassLoader)
*/
protected void resetCommonCaches() {
ReflectionUtils.clearCache();
AnnotationUtils.clearCache();
ResolvableType.clearCache();
CachedIntrospectionResults.clearClassLoader(getClassLoader());
}
@Override
public void clearResourceCaches() {
super.clearResourceCaches();
if (this.resourcePatternResolver instanceof PathMatchingResourcePatternResolver pmrpr) {
pmrpr.clearCache();
}
}
/**
* 向 JVM 运行时注册一个名为 {@code SpringContextShutdownHook} 的关闭钩子 {@linkplain Thread#getName()},
* 在 JVM 关闭时关闭此上下文,除非当时它已经关闭。
* <p>委托给 {@code doClose()} 执行实际的关闭过程。
* @see Runtime#addShutdownHook
* @see ConfigurableApplicationContext#SHUTDOWN_HOOK_THREAD_NAME
* @see #close()
* @see #doClose()
*/
@Override
public void registerShutdownHook() {
if (this.shutdownHook == null) {
// 尚未注册关闭挂钩。
this.shutdownHook = new Thread(SHUTDOWN_HOOK_THREAD_NAME) {
@Override
public void run() {
if (isStartupShutdownThreadStuck()) {
active.set(false);
return;
}
startupShutdownLock.lock();
try {
doClose();
}
finally {
startupShutdownLock.unlock();
}
}
};
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
}
}
/**
* 确定活动的启动/关闭线程当前是否卡住,例如,通过用户组件中的{@code System.exit}调用。
*/
private boolean isStartupShutdownThreadStuck() {
Thread activeThread = this.startupShutdownThread;
if (activeThread != null && activeThread.getState() == Thread.State.WAITING) {
// 无限期等待:可能是Thread.join等,或者System.exit
activeThread.interrupt();
try {
// 只留一点时间让中断显示效果
Thread.sleep(1);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
if (activeThread.getState() == Thread.State.WAITING) {
// 已中断但仍在等待:很可能是 System.exit 调用
return true;
}
}
return false;
}
/**
* 关闭此应用程序上下文,销毁其bean工厂中的所有bean。
* <p>将实际关闭过程委托给 {@code doClose()} 。如果已注册,还会删除 JVM 关闭钩子,因为不再需要它。
* @see #doClose()
* @see #registerShutdownHook()
*/
@Override
public void close() {
if (isStartupShutdownThreadStuck()) {
this.active.set(false);
return;
}
this.startupShutdownLock.lock();
try {
this.startupShutdownThread = Thread.currentThread();
doClose();
// 如果我们注册了 JVM 关闭钩子,现在就不再需要它了:
// 我们已经明确关闭了上下文。
if (this.shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
}
catch (IllegalStateException ex) {
// 忽略 - VM 已关闭
}
}
}
finally {
this.startupShutdownThread = null;
this.startupShutdownLock.unlock();
}
}
/**
* 实际执行上下文关闭:发布 ContextClosedEvent 并销毁该应用程序上下文的 bean 工厂中的单例。
* <p>由 {@code close()} 和 JVM 关闭钩子(如果有)调用。
* @see org.springframework.context.event.ContextClosedEvent
* @see #destroyBeans()
* @see #close()
* @see #registerShutdownHook()
*/
protected void doClose() {
// 检查是否有必要进行实际的关闭尝试...
if (this.active.get() && this.closed.compareAndSet(false, true)) {
if (logger.isDebugEnabled()) {
logger.debug("Closing " + this);
}
try {
// 发布关闭事件。
publishEvent(new ContextClosedEvent(this));
}
catch (Throwable ex) {
logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);
}
// 停止所有生命周期 bean,以避免单个销毁过程中的延迟。
if (this.lifecycleProcessor != null) {
try {
this.lifecycleProcessor.onClose();
}
catch (Throwable ex) {
logger.warn("Exception thrown from LifecycleProcessor on context close", ex);
}
}
// 销毁上下文 BeanFactory 中所有缓存的单例。
destroyBeans();
// 关闭该上下文本身的状态。
closeBeanFactory();
// 如果子类愿意的话,让他们做一些最后的清理工作......
onClose();
// 重置常见的内省缓存以避免类引用泄漏。
resetCommonCaches();
// 将本地应用程序侦听器重置为预刷新状态。
if (this.earlyApplicationListeners != null) {
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// 重置内部委托。
this.applicationEventMulticaster = null;
this.messageSource = null;
this.lifecycleProcessor = null;
// 切换至非活动状态。
this.active.set(false);
}
}
/**
* 用于销毁此上下文管理的所有 bean 的模板方法。默认实现会销毁此上下文中的所有缓存单例,
* 调用 {@code DisposableBean.destroy()} 和/或指定的“销毁方法”。
* <p>可以重写以在标准单例销毁之前或之后添加特定于上下文的bean销毁步骤,同时上下文的BeanFactory仍处于活动状态。
* @see #getBeanFactory()
* @see org.springframework.beans.factory.config.ConfigurableBeanFactory#destroySingletons()
*/
protected void destroyBeans() {
getBeanFactory().destroySingletons();
}
/**
* 可以重写的模板方法,以添加特定于上下文的关闭工作。默认实现为空。
* <p>在此上下文的BeanFactory关闭后,在{@link#doClose}的关闭过程结束时调用。
* 在BeanFactory仍处于活动状态时,如果需要执行自定义关闭逻辑,
* 请重写{@link#destroyBean()}方法。
*/
protected void onClose() {
// 子类实现:默认情况下不执行任何操作。
}
@Override
public boolean isClosed() {
return this.closed.get();
}
@Override
public boolean isActive() {
return this.active.get();
}
/**
* 断言此上下文的 BeanFactory 当前处于活动状态,如果不是,则抛出 {@link IllegalStateException}。
* <p>由依赖于活动上下文的所有{@link BeanFactory}委托方法调用,特别是所有bean访问器方法。
* <p>默认实现检查此上下文的{@link #isActive() 'active'}状态。
* 如果{@link #getBeanFactory()}本身抛出异常,则可以覆盖更具体的检查或无操作。
*/
protected void assertBeanFactoryActive() {
if (!this.active.get()) {
if (this.closed.get()) {
throw new IllegalStateException(getDisplayName() + " has been closed already");
}
else {
throw new IllegalStateException(getDisplayName() + " has not been refreshed yet");
}
}
}
//---------------------------------------------------------------------
// BeanFactory接口的实现
//---------------------------------------------------------------------
@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();
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);
}
//---------------------------------------------------------------------
// ListableBeanFactory接口的实现
//---------------------------------------------------------------------
@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 <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType, boolean allowEagerInit) {
assertBeanFactoryActive();
return getBeanFactory().getBeanProvider(requiredType, allowEagerInit);
}
@Override
public <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType, boolean allowEagerInit) {
assertBeanFactoryActive();
return getBeanFactory().getBeanProvider(requiredType, allowEagerInit);
}
@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);
}
@Override
@Nullable
public <A extends Annotation> A findAnnotationOnBean(
String beanName, Class<A> annotationType, boolean allowFactoryBeanInit)
throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().findAnnotationOnBean(beanName, annotationType, allowFactoryBeanInit);
}
@Override
public <A extends Annotation> Set<A> findAllAnnotationsOnBean(
String beanName, Class<A> annotationType, boolean allowFactoryBeanInit)
throws NoSuchBeanDefinitionException {
assertBeanFactoryActive();
return getBeanFactory().findAllAnnotationsOnBean(beanName, annotationType, allowFactoryBeanInit);
}
//---------------------------------------------------------------------
// HierarchicalBeanFactory接口的实现
//---------------------------------------------------------------------
@Override
@Nullable
public BeanFactory getParentBeanFactory() {
return getParent();
}
@Override
public boolean containsLocalBean(String name) {
return getBeanFactory().containsLocalBean(name);
}
/**
* 如果父上下文实现了ConfigurableApplicationContext,则返回其内部bean工厂。否则,返回父上下文本身。
* @see org.springframework.context.ConfigurableApplicationContext#getBeanFactory
*/
@Nullable
protected BeanFactory getInternalParentBeanFactory() {
return (getParent() instanceof ConfigurableApplicationContext cac ?
cac.getBeanFactory() : getParent());
}
//---------------------------------------------------------------------
// MessageSource接口的实现
//---------------------------------------------------------------------
@Override
@Nullable
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);
}
/**
* 返回上下文使用的内部 MessageSource。
* @return 内部 MessageSource(绝不是 {@code null})
* @throws IllegalStateException 如果上下文尚未初始化
*/
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;
}
/**
* 如果父上下文也是 AbstractApplicationContext,则返回其内部消息源;否则,返回父上下文本身。
*/
@Nullable
protected MessageSource getInternalParentMessageSource() {
return (getParent() instanceof AbstractApplicationContext abstractApplicationContext ?
abstractApplicationContext.messageSource : getParent());
}
//---------------------------------------------------------------------
// ResourcePatternResolver接口的实现
//---------------------------------------------------------------------
@Override
public Resource[] getResources(String locationPattern) throws IOException {
return this.resourcePatternResolver.getResources(locationPattern);
}
//---------------------------------------------------------------------
// Lifecycle接口的实现
//---------------------------------------------------------------------
@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());
}
//---------------------------------------------------------------------
// 必须由子类实现的抽象方法
//---------------------------------------------------------------------
/**
* 子类必须实现此方法才能执行实际的配置加载。该方法由 {@link #refresh()} 在任何其他初始化工作之前调用。
* <p>子类将创建一个新的 Bean 工厂并保存对它的引用,或者返回它所保存的单个 BeanFactory 实例。在后一种情况下,
* 如果多次刷新上下文,通常会抛出 IllegalStateException。
* @throws BeansException 如果bean工厂初始化失败
* @throws IllegalStateException 如果已经初始化并且不支持多次刷新尝试
*/
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
/**
* 子类必须实现此方法来释放其内部 bean 工厂。
* 在所有其他关闭工作之后,此方法由 {@link #close()} 调用。
* <p>不应抛出异常,而应记录关机失败。
*/
protected abstract void closeBeanFactory();
/**
* 子类必须在此处返回其内部 bean 工厂。他们应该有效地实现查找,以便可以重复调用它而不会造成性能损失。
* <p>注意: 子类应该在返回内部 bean 工厂之前检查上下文是否仍然处于活动状态。一旦上下文关闭,内部工厂通常应被视为不可用。
* @return 此应用程序上下文的内部 bean 工厂(绝不是 {@code null})
* @throws IllegalStateException 如果上下文还没有内部 bean 工厂(通常如果从未调用过 {@link #refresh()})或者上下文已经关闭
* @see #refreshBeanFactory()
* @see #closeBeanFactory()
*/
@Override
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
/**
* 返回有关此上下文的信息。
*/
@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();
}
}