spring源码分析—— 一
之前看源码的时候还是使用spring时期,当时没有进行一个记录,这里重新开始分析,这里我采用springboot2.0.x环境是idea,直接使用jar包进行源码分析,不再去官网特意下载spirng的源码,有需要的可以自行去spring的官网的github上下载spring的源码
这里贴出spring官网http://spring.io/
以及spring的一个GitHub地址https://github.com/spring-projects/spring-framework
当然这里我也说一下当我们在进行一个框架源码分析的时候我们最好是已经可以熟练使用该框架,对于框架的使用这里不会赘述,如果不知道spring如何使用的,可以去看张开涛的跟我学系列的《跟我学spring》,里面讲的非常的清楚,我个人学习spring的用法的时候参考了他的博客,当然其实最好的学习一个框架的方式是,首先我们得理解,这个框架是什么,干什么,怎么用,我们一定要带着这3个问题去学习一个框架,而学习一个框架最好的方式其实是看官方文档,当然也不限于框架,包括mysql,redis,elasticsearch,docker等等这些东西,我们一定要去看它的官方文档,知道官方定义,当然官方文档一般都是纯英文,也有中文的文档,比如dubbo,这里不要觉得自己英语不好就不去看,如果说你的英语确实不好,比如我,英语真的是硬伤,说实话这个很简单,谷歌浏览器自带翻译,谷歌翻译这种文档可以说已经很友好了,所以我们一定要去看官方文档,其实你不知道的很多东西而别人却知道在官方文档里都写的清清楚楚的,第一次看可能会很痛苦,后面慢慢就会适应的。这里就不再废话了进入我们的主题
大家都知道springboot是使用run方法启动,那么我们来看看SpringApplication这个类中的run方法
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
//创建spring应用程序上下文
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
这里我们忽略一些其他的一些初始化方法看主要的方法
这里我们看到有一个方法
context = createApplicationContext();
进入该方法
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch (this.webApplicationType) {
case SERVLET:
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
}
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, "
+ "please specify an ApplicationContextClass",
ex);
}
}
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
因为我这里使用的是springMVC那么这里的webApplicationType是哪里设置的呢
webApplication是一个枚举其中有这样的方法
static WebApplicationType deduceFromClasspath() {
if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null)
&& !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
return WebApplicationType.REACTIVE;
}
for (String className : SERVLET_INDICATOR_CLASSES) {
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
return WebApplicationType.SERVLET;
}
spring会自己通过加载对应的环境中的必须的类去判断属于什么环境,这里是springMVC所以最后返回了SERVLET也就是servlet
那么回到刚才的方法也就会走到
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
那么DEFAULT_SERVLET_WEB_CONTEXT_CLASS是什么呢
是在SpingApplication中的一个成员变量
/**
* The class name of application context that will be used by default for web
* environments.
*/
public static final String DEFAULT_SERVLET_WEB_CONTEXT_CLASS = "org.springframework.boot."
+ "web.servlet.context.AnnotationConfigServletWebServerApplicationContext";
那么这里使用反射获取到了我们的AnnotationConfigServletWebServerApplicationContext这样一个spring的上下文
相当于已经创建了我们的一个Bean工厂
这里我们需要知道ConfigurableApplicationContext的一个关系
我们继续往下看
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
这个是初始化springboot的一些需要初始化的东西
这里重点是spring所以这里大家可以自行去看这里面springboot做了一些什么
好的我们终于来到了我们的重点方法
refreshContext(context);
进入该方法
private void refreshContext(ConfigurableApplicationContext context) {
refresh(context);
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
}
再进入refresh(context);
protected void refresh(ApplicationContext applicationContext) {
Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
((AbstractApplicationContext) applicationContext).refresh();
}
再进入refresh();
这里我们有3个,看过到这里如果有看过源码经验的或者对oop有深入理解的会直接进第一个抽象类,因为第二个和第三个必定都是第一个的子类,当然没有这样的经验也无妨,因为这个方法也有可能会被重写,那么我们因为是MVC所以我们进入第三个ServletWebServerApplicationContext
@Override
public final void refresh() throws BeansException, IllegalStateException {
try {
super.refresh();
}
catch (RuntimeException ex) {
stopAndReleaseWebServer();
throw ex;
}
}
果然我们看到重写了一些东西并调用了父类的方法,那么我们进入父类方法
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//准备此上下文以进行刷新。
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//告诉子类刷新内部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的工厂处理器。
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//注册拦截bean创建的bean处理器。
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//初始化此上下文的消息源。
initMessageSource();
// Initialize event multicaster for this context.
//初始化此上下文的多路广播事件。
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//在特定上下文子类中初始化其他特殊bean。
onRefresh();
// Check for listener beans and register them.
//检查监听器bean并注册它们。
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//实例化所有剩余(非延迟初始化)单例。
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
//最后一步:发布相应的事件。
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
//摧毁已经创建的单例对象以避免资源浪费。
destroyBeans();
// Reset 'active' flag.
//重置'有效'标志。
cancelRefresh(ex);
// Propagate exception to caller.
//向调用者传播异常。
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
//重置Spring核心中常见的内省缓存,因为我们
//可能不再需要单例bean的元数据了...
resetCommonCaches();
}
}
}
终于我们来到了AbstractApplicationContext,这里已经是spring的核心流程了,英文是我用谷歌翻译的,我的英文确实也不是很好,所以需要借助到翻译工具。
那么进入第一个方法prepareRefresh();
很好又是三个实现,我们继续走第三个
@Override
protected void prepareRefresh() {
this.scanner.clearCache();
super.prepareRefresh();
}
这里首先清除了Cache缓存,然后调用父类,我们直接进入super
/**
* Prepare this context for refreshing, setting its startup date and
* active flag as well as performing any initialization of property sources.
*/
protected void prepareRefresh() {
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());
}
}
// Initialize any placeholder property sources in the context environment
//在上下文环境中初始化任何占位符属性源
initPropertySources();
// Validate that all properties marked as required are resolvable
// see ConfigurablePropertyResolver#setRequiredProperties
//验证标记为必需的所有属性是否可解析
//请参阅ConfigurablePropertyResolver #setRequiredProperties
getEnvironment().validateRequiredProperties();
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
//允许收集早期的ApplicationEvents,
//一旦多播器可用就会发布......
this.earlyApplicationEvents = new LinkedHashSet<>();
}
这里是加载servlet的一些资源配置,不再跟入,有兴趣的可以自行跟入
回到上级
// Prepare this context for refreshing.
//准备此上下文以进行刷新。
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//告诉子类刷新内部bean工厂。
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//准备bean工厂以在此上下文中使用。
prepareBeanFactory(beanFactory);
这里第二个方法
obtainFreshBeanFactory进入该方法
/**
* Tell the subclass to refresh the internal bean factory.
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
refreshBeanFactory()存在2个实现
给出两个类的一个关系
其中AbstractRefreshableApplicationContext是spring的一系列实现,比如之前的XML的实现以及定义的Bean解析等等使用的是该子类
这里我们springBoot默认启动的是GenericApplicationContext下的子类
两个类不同的实现方法这里贴出
AbstractRefreshableApplicationContext.refreshBeanFactory()
/**
* This implementation performs an actual refresh of this context's underlying
* bean factory, shutting down the previous bean factory (if any) and
* initializing a fresh bean factory for the next phase of the context's lifecycle.
*/
@Override
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
//这里开始加载BeanDefinitions
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
GenericApplicationContext.refreshBeanFactory()
/**
* Do nothing: We hold a single internal BeanFactory and rely on callers
* to register beans through our public methods (or the BeanFactory's).
* @see #registerBeanDefinition
什么都不做:我们持有一个内部BeanFactory并依赖调用者通过我们的公共方法(或BeanFactory)来注册
bean。 @see #registerBeanDefinition
*/
@Override
protected final void refreshBeanFactory() throws IllegalStateException {
if (!this.refreshed.compareAndSet(false, true)) {
throw new IllegalStateException(
"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
}
this.beanFactory.setSerializationId(getId());
}
可以看到这里其实什么都没有做,是在后期通过扫描注解再解析成BeanDefinition放入容器中
最后方法返回beanFactory是GenericApplicationContext中的DefaultListableBeanFactory
GenericApplicationContext在上面已经给出了关系它是AnnotationConfigServletWebServerApplicationContext的父类
这里给出DefaultListableBeanFactory关系图
这里可以自行深入,不再赘述,进入我们的第三个方法prepareBeanFactory(beanFactory);
/**
* Configure the factory's standard context characteristics,
* such as the context's ClassLoader and post-processors.
* @param beanFactory the BeanFactory to configure
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
//告诉内部bean工厂使用上下文的类加载器等。
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
//使用上下文回调配置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 interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
// BeanFactory接口未在普通工厂中注册为可解析类型。
// MessageSource注册(并找到自动装配)作为bean。
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
注册早期后处理器以检测内部bean作为ApplicationListeners。
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
//检测到LoadTimeWeaver并准备编织(如果找到)。
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
//为类型匹配设置临时ClassLoader。
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
//注册默认环境bean。
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
这里我们可以看到spring用了一个Set去装不进行依赖注入的接口ignoreDependencyInterface(Class clazz);方法就是往下面的HashSet中放入接口
/**
* Dependency interfaces to ignore on dependency check and autowire, as Set of
* Class objects. By default, only the BeanFactory interface is ignored.
*/
private final Set<Class<?>> ignoredDependencyInterfaces = new HashSet<>();
那么同样的我们来看registerResolvableDependency方法可以看到往一个Map中put了依赖关系
从依赖类型映射到相应的自动装配值
//---------------------------------------------------------------------
// Implementation of ConfigurableListableBeanFactory interface
//---------------------------------------------------------------------
@Override
public void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue) {
Assert.notNull(dependencyType, "Dependency type must not be null");
if (autowiredValue != null) {
if (!(autowiredValue instanceof ObjectFactory || dependencyType.isInstance(autowiredValue))) {
throw new IllegalArgumentException("Value [" + autowiredValue +
"] does not implement specified dependency type [" + dependencyType.getName() + "]");
}
this.resolvableDependencies.put(dependencyType, autowiredValue);
}
}
其map为
/** Map from dependency type to corresponding autowired value. */
private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16);
我们继续往下走走进registerSingleton方法
这里会走DefaultListableBeanFactory中为什么不走下面的呢DefaultListableBeanFactory是DefaultSingletonBeanRegistry的子类
并且我们传入这里的参数正是DefaultListableBeanFactory进入方法
@Override
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
super.registerSingleton(beanName, singletonObject);
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
if (!this.beanDefinitionMap.containsKey(beanName)) {
Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames.size() + 1);
updatedSingletons.addAll(this.manualSingletonNames);
updatedSingletons.add(beanName);
this.manualSingletonNames = updatedSingletons;
}
}
}
else {
// Still in startup registration phase
if (!this.beanDefinitionMap.containsKey(beanName)) {
this.manualSingletonNames.add(beanName);
}
}
clearByTypeCache();
}
进入父类
@Override
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
Assert.notNull(beanName, "Bean name must not be null");
Assert.notNull(singletonObject, "Singleton object must not be null");
synchronized (this.singletonObjects) {
Object oldObject = this.singletonObjects.get(beanName);
if (oldObject != null) {
throw new IllegalStateException("Could not register object [" + singletonObject +
"] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
}
addSingleton(beanName, singletonObject);
}
}
这里有一个map专门装我们的单例bean如下
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
这里addSingleton方法我们跟入
/**
* Add the given singleton object to the singleton cache of this factory.
* <p>To be called for eager registration of singletons.
*将给定的单例对象添加到此工厂的单例缓存中。
* @param beanName the name of the bean
* @param singletonObject the singleton object
*/
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
我们可以看到这样的一系列的集合操作这里我给出所有的集合
/** Cache of singleton objects: bean name to bean instance. */
/**单例对象的缓存:bean名称到bean实例。*/
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */
/**单例工厂的缓存:bean名称为ObjectFactory。*/
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */
/**早期单例对象的缓存:bean名称到bean实例。*/
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
/** Set of registered singletons, containing the bean names in registration order. */
/**一组注册单例,包含注册顺序中的bean名称。*/
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
走完add后我们回来DefaultListableBeanFactory的registerSingleton方法
super.registerSingleton(beanName, singletonObject);
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
if (!this.beanDefinitionMap.containsKey(beanName)) {
Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames.size() + 1);
updatedSingletons.addAll(this.manualSingletonNames);
updatedSingletons.add(beanName);
this.manualSingletonNames = updatedSingletons;
}
}
}
else {
// Still in startup registration phase
if (!this.beanDefinitionMap.containsKey(beanName)) {
this.manualSingletonNames.add(beanName);
}
}
clearByTypeCache();
这里的hasBeanCreationStarted()涉及到一个Map下面贴出
/** Names of beans that have already been created at least once. */
/**至少已创建一次的bean的名称。*/
private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256));
这里是false所以会走else的代码块
关于beanDefinitonMap和manualSingletonNames下面我也贴出来
/** Map of bean definition objects, keyed by bean name. */
/** bean定义对象的映射,由bean名称键入。* /
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
/** List of names of manually registered singletons, in registration order. */
/**按登记顺序列出的单例对象名字。*/
private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16);
这里的beanName为
而Map中为
所以这里条件判断为ture
往manualSingletonNames中加入beanName
下面进入clearByTypeCache();
/**
* Remove any assumptions about by-type mappings.
* 删除有关按类型映射的任何假设。
*/
private void clearByTypeCache() {
this.allBeanNamesByType.clear();
this.singletonBeanNamesByType.clear();
}
下面给出2个Map的定义
/** Map of singleton and non-singleton bean names, keyed by dependency type. */
/**单例和非单例bean名称的映射,由依赖类型键入*/
private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);
/** Map of singleton-only bean names, keyed by dependency type. */
/**仅依赖于单一的bean名称的映射,由依赖关系类型键入*/
private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64);
到这里prepareBeanFactory方法完全分析完毕,那么下一节我们将继续分析剩下的方法,这里再贴一次
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//准备此上下文以进行刷新。
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//告诉子类刷新内部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的工厂处理器。
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//注册拦截bean创建的bean处理器。
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//初始化此上下文的消息源。
initMessageSource();
// Initialize event multicaster for this context.
//初始化此上下文的多路广播事件。
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//在特定上下文子类中初始化其他特殊bean。
onRefresh();
// Check for listener beans and register them.
//检查监听器bean并注册它们。
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//实例化所有剩余(非延迟初始化)单例。
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
//最后一步:发布相应的事件。
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
//摧毁已经创建的单例对象以避免资源浪费。
destroyBeans();
// Reset 'active' flag.
//重置'有效'标志。
cancelRefresh(ex);
// Propagate exception to caller.
//向调用者传播异常。
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
//重置Spring核心中常见的内省缓存,因为我们
//可能不再需要单例bean的元数据了...
resetCommonCaches();
}
}
}