1.AbstractApplicationContext#refresh主流程
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
// 刷新容器 预准备工作
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 获取一个全新的BeanFactory接口实例
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 预处理bf.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 空方法,留给子类实现,用于注册一些 beanFactoryPostProcessor
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 查找 并 执行 bfpp 后处理器
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册后处理器
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
// 初始化事件传播器。
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 留给子类去实现的,在这个方法内,你可以硬编码提供一些组件,
// 比如说 提供了一些Listeners
onRefresh();
// Check for listener beans and register them.
// 注册通过配置提供的Listener,这些监听器 最终都会注册到 Multicaster内。
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 实例化非懒加载状态的单实例。
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 完成刷新 后做的一些事情,主要是启动生命周期对象。
finishRefresh();
}
2.AbstractApplicationContext#prepareRefresh
protected void prepareRefresh() {
// Switch to 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());
}
}
// Initialize any placeholder property sources in the context environment.
// 留给子类扩展
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
// 校验必须有的环境变量
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}
示例:
public class Main {
public static void main(String[] args) {
ApplicationContext ac =
new MyClassPathXmlApplicationContext("spring-required-properties-test.xml");
}
}
public class MyClassPathXmlApplicationContext extends ClassPathXmlApplicationContext {
public MyClassPathXmlApplicationContext(String... configLocations) {
super(configLocations);
}
/**
* 重写AbstractApplicationContext.initPropertySources() 方法
* 在此指定需要验证非空的环境变量
*/
@Override
protected void initPropertySources() {
getEnvironment().setRequiredProperties("LG_HOME");
}
}
如果必需的属性没有设置,就会报错:
Exception in thread "main" org.springframework.core.env.MissingRequiredPropertiesException: The following properties were declared as required but could not be resolved: [LG_HOME]
at org.springframework.core.env.AbstractPropertyResolver.validateRequiredProperties(AbstractPropertyResolver.java:145)
at org.springframework.core.env.AbstractEnvironment.validateRequiredProperties(AbstractEnvironment.java:519)
at org.springframework.context.support.AbstractApplicationContext.prepareRefresh(AbstractApplicationContext.java:605)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:520)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:144)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:95)
at com.wz.spring.requiredProperties.MyClassPathXmlApplicationContext.(MyClassPathXmlApplicationContext.java:8)
at com.wz.spring.requiredProperties.Main.main(Main.java:8)
FAILURE: Build failed with an exception.
3.AbstractApplicationContext#obtainFreshBeanFactory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
protected final void refreshBeanFactory() throws BeansException {
// 条件成立:说明当前applicationContext内部拥有一个beanFactory接口实例,
// 咱们需要将该beanFactory实例完全释放掉。
if (hasBeanFactory()) {
// 销毁原beanFactory内部的实例的流程。
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
// 加载bd信息,这一步完成之后,所有的配置信息(bd)就注册到 bf内了。
loadBeanDefinitions(beanFactory);
// 保留引用。
this.beanFactory = beanFactory;
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
3.1 重点分析一下bean的销毁逻辑
protected void destroyBeans() {
// 销毁原beanFactory内部的单实例。
getBeanFactory().destroySingletons();
}
public void destroySingletons() {
super.destroySingletons();
updateManualSingletonNames(Set::clear, set -> !set.isEmpty());
clearByTypeCache();
}
public void destroySingletons() {
if (logger.isTraceEnabled()) {
logger.trace("Destroying singletons in " + this);
}
synchronized (this.singletonObjects) {
// 设置该属性,表示当前beanFactory状态转变为了销毁状态。
this.singletonsCurrentlyInDestruction = true;
}
// disposable ? 创建单实例时,会检查当前单实例类型
// 是否实现了DisposableBean接口,如果实现了该接口,
// 对应,容器销毁时,需要执行该bean.destroy() 方法。
String[] disposableBeanNames;
synchronized (this.disposableBeans) {
disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
}
for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
destroySingleton(disposableBeanNames[i]);
}
this.containedBeanMap.clear();
this.dependentBeanMap.clear();
this.dependenciesForBeanMap.clear();
clearSingletonCache();
}
public void destroySingleton(String beanName) {
// Remove a registered singleton of the given name, if any.
// 清空3级缓存 + registeredSingletons 里面 对应当前beanName的数据。
removeSingleton(beanName);
// Destroy the corresponding DisposableBean instance.
DisposableBean disposableBean;
synchronized (this.disposableBeans) {
// 注册时会向 disposableBeans 内部存放 实现了 DisposableBean 接口的 bean
disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
}
destroyBean(beanName, disposableBean);
}
protected void destroyBean(String beanName, @Nullable DisposableBean bean) {
// Trigger destruction of dependent beans first...
Set dependencies;
// dependentBeanMap ? 保存的是依赖当前 bean 的其它bean信息。
//比如说:b/c/d 这三个bean依赖了a,那么dependentBeanMap 内部 就应该有这样一个数据:
//{key:a, value: {b,c,d}}
synchronized (this.dependentBeanMap) {
// Within full synchronization in order to guarantee a disconnected Set
dependencies = this.dependentBeanMap.remove(beanName);
}
if (dependencies != null) {
if (logger.isTraceEnabled()) {
logger.trace("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
}
// 因为依赖对象要被回收了,所以 依赖当前bean的其它对象,
// 都要执行destroySingleton逻辑。
for (String dependentBeanName : dependencies) {
destroySingleton(dependentBeanName);
}
}
// Actually destroy the bean now...
if (bean != null) {
try {
//执行当前bean的销毁方法。
bean.destroy();
}
catch (Throwable ex) {
if (logger.isWarnEnabled()) {
logger.warn("Destruction of bean with name '" + beanName + "' threw an exception", ex);
}
}
}
// Trigger destruction of contained beans...
Set containedBeans;
synchronized (this.containedBeanMap) {
// Within full synchronization in order to guarantee a disconnected Set
containedBeans = this.containedBeanMap.remove(beanName);
}
if (containedBeans != null) {
for (String containedBeanName : containedBeans) {
destroySingleton(containedBeanName);
}
}
// Remove destroyed bean from other beans' dependencies.
synchronized (this.dependentBeanMap) {
for (Iterator>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) {
Map.Entry> entry = it.next();
Set dependenciesToClean = entry.getValue();
dependenciesToClean.remove(beanName);
if (dependenciesToClean.isEmpty()) {
it.remove();
}
}
}
// Remove destroyed bean's prepared dependency information.
// 比如说a 它依赖了 w,x ,那么对应dependenciesForBeanMap 就应该有:
// {a, {w,x}}
this.dependenciesForBeanMap.remove(beanName);
}
4.AbstractApplicationContext#prepareBeanFactory
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
// 给当前bf设置一个类加载器,用于加载bd的class信息。
beanFactory.setBeanClassLoader(getClassLoader());
// Spring EL 表达式,这个表达式谁解析?
// StandardBeanExpressionResolver . #{object.a}
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
//BeanWrapper 本身就是属性编辑器注册中心,
// 属性编辑器作用于beanWrapper内部管理的真实bean 注入 字段值时,
//当某个字段对应的类型 在 BeanWrapper内 有对应的 属性编辑器,
// 那么对应类型的字段值 就由该属性编辑器 代理写入。
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
// 添加后处理器,该后处理器 主要用于向bean内部注入一些 框架级别的实例,
// 比如说:环境变量、ApplicationContext
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//忽略指定类型的依赖。
//意思就是说,bean内部有这些类型的字段的话,这些字段 不参与 依赖注入。
// 统一放在上面的ApplicationContextAwareProcessor里面处理
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
// 该后处理器 将配置的监听者 注册到 ac中。
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
4.1 属性编辑器
属性编辑器:属性注入进Bean实例之前,可以通过属性编辑器操作一下。
public class DatePropertyEditorRegistrar implements PropertyEditorRegistrar {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new DatePropertyEditor());
}
}
public class DatePropertyEditor extends PropertyEditorSupport {
private String format = "yyyy-MM-dd";
public void setFormat(String format) {
this.format = format;
}
public void setAsText(String arg0) {
System.out.println("arg0:" + arg0);
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
Date d = sdf.parse(arg0);
this.setValue(d);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
4.2 ApplicationListenerDetector
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class> beanType, String beanName) {
if (ApplicationListener.class.isAssignableFrom(beanType)) {
this.singletonNames.put(beanName, beanDefinition.isSingleton());
}
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
return bean;
}
/**
* 判断当前创建出来的bean实例 是否是 实现了 ApplicationListener 接口的 实例,如果是,
* 当前bean就是一个 事件监听器 对象,需要把监听者注册到 ac 中。
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof ApplicationListener) {
// potentially not detected as a listener by getBeanNamesForType retrieval
Boolean flag = this.singletonNames.get(beanName);
if (Boolean.TRUE.equals(flag)) {
// singleton bean (top-level or inner): register on the fly
this.applicationContext.addApplicationListener((ApplicationListener>) bean);
}
else if (Boolean.FALSE.equals(flag)) {
if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
// inner bean with other scope - can't reliably process events
logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
"but is not reachable for event multicasting by its containing ApplicationContext " +
"because it does not have singleton scope. Only top-level listener beans are allowed " +
"to be of non-singleton scope.");
}
this.singletonNames.remove(beanName);
}
}
return bean;
}
5.AbstractApplicationContext#invokeBeanFactoryPostProcessors
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
// 存储已经执行过的bfpp beanName
Set processedBeans = new HashSet<>();
// 条件成立:说明当前bf是bd注册中心。bd全部注册到bf内。
if (beanFactory instanceof BeanDefinitionRegistry) {
// 将bf 转换成 bdRegistry。
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 规整的 普通的 PostProcessor集合。
List regularPostProcessors = new ArrayList<>();
// 存储 BeanDefinitionRegistryPostProcessor 集合。
// BeanDefinitionRegistryPostProcessor 这种类型的容器后处理器
// 可以再向容器内 手动硬编码注册一些bd。
List registryProcessors = new ArrayList<>();
// 处理ApplicationContext上面 硬编码注册的一些 bfpp 处理器。
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
// 这里调用 可以向 bf 内部再次注册一些 bd信息。
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
//因为当前postProcessor非registry类型,
// 即当前postProcessor是个普通的。就加入到普通集合,后续会统一执行一些方法。
regularPostProcessors.add(postProcessor);
}
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
// 临时的,当前阶段的 registry后处理器集合。
List currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
//使用bf获取BeanDefinitionRegistryPostProcessor类型的全部beanName
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
//处理每个beanName,每个beanName其实都是
// BeanDefinitionRegistryPostProcessor。
for (String ppName : postProcessorNames) {
// 判断对应的bean是否实现了 主排序接口PriorityOrdered ,
// 如果实现了,就让该 bdrpp 添加到 currentRegistryProcessors。
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 因为接下来马上就是要执行 bfrpp 的 registry 相关接口方法,
// 所以将beanName添加到processedBeans 表示已执行。
processedBeans.add(ppName);
}
}
//排序,根据order值进行 升序排序。
sortPostProcessors(currentRegistryProcessors, beanFactory);
//添加到registry类型后处理器集合内。
registryProcessors.addAll(currentRegistryProcessors);
// 调用每个bdrpp的postProcessBeanDefinitionRegistry 方法,
// 向bf内注册bd信息。
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 清空集合。
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
//!processedBeans.contains(ppName) 确保每个bdrpp只执行一次 注册 bd的逻辑。
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// 控制while是否需要再次循环,因为循环内就是查找并执行
// bdrpp后处理器的registry相关的接口方法。
// 接口方法执行之后 会向bf 内注册 bd,再次注册的bd
// 也有可能是 bdrpp 类型,所以,需要该变量控制while循环。
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// 执行硬编码提供的【beanFactoryPostProcessor】接口实现类的
// postProcessBeanFactory() 方法。
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
//上面的代码处理了:硬编码提供的bfpp 和 bdrpp 这两种类型的bfpp。
//还有普通的bfpp需要处理。
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// 获取容器内注册的bfpp类型的 beanName 数组集合。
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List priorityOrderedPostProcessors = new ArrayList<>();
List orderedPostProcessorNames = new ArrayList<>();
List nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}
6.AbstractApplicationContext#initApplicationEventMulticaster
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 条件成立:说明用户自定义了事件传播器。
// 咱们可以实现ApplicationEventMulticaster接口,
// 写一款自己的事件传播器,通过bean的方式提供给Spring。
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() + "]");
}
}
}
7.AbstractApplicationContext#registerListeners
protected void registerListeners() {
// Register statically specified listeners first.
// 注册硬编码提供的监听器。
for (ApplicationListener> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
// 注册通过配置提供的Listener。
// 用户可以通过beanDefinition的方式 提供 Listener。
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
Set earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
8.AbstractApplicationContext#finishBeanFactoryInitialization
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
// 冻结配置信息,冻结bd信息。 冻结之后,就无法再向bf内注册bd。
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
// 预初始化非懒加载状态的单实例。
beanFactory.preInstantiateSingletons();
}
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
// 获取bd信息。
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 条件成立:说明bd是非抽象 且 是单实例 且 非懒加载,就需要预先实例化出来。
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//当前beanDefinition对应的class可能是 普通的,也可能是 FactoryBean。
//条件成立:说明当前bd的class是FactoryBean
if (isFactoryBean(beanName)) {
// 获取FactoryBean实例本身。
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
FactoryBean> factory = (FactoryBean>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(
(PrivilegedAction) ((SmartFactoryBean>) factory)::isEagerInit,
getAccessControlContext());
}
else {
// 控制FactoryBean内部管理的真实bean,在refresh阶段 是否也初始化。
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean>) factory).isEagerInit());
}
// 需要初始化FactoryBean管理的Bean
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
getBean(beanName);
}
}
9.AbstractApplicationContext#finishRefresh
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
// Initialize lifecycle processor for this context.
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
9.1 initLifecycleProcessor()
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 {
// Spring 默认提供的生命周期处理器。
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
// 将生命周期处理器 注册到 bf的一级缓存内。
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
if (logger.isTraceEnabled()) {
logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
}
}
}
9.2 DefaultLifecycleProcessor#onRefresh
public void onRefresh() {
startBeans(true);
this.running = true;
}
/**
* autoStartupOnly ?
* true:表示只启动 SmartLifecycle 生命周期对象,并且启动 SmartLifecycle对象它的autoStartup是true。
* 不会启动 普通的 lifecycle 生命周期对象。
*
* false:全部启动。
*/
private void startBeans(boolean autoStartupOnly) {
// 获取到所有实现了 Lifecycle接口的对象,
// 包装到map内,key是beanName,value 是 lifecycle对象。
Map lifecycleBeans = getLifecycleBeans();
// 因为生命周期对象 可能依赖其它生命周期对象的执行结果,
// 所以需要执行顺序,靠什么实现呢?
// 靠 phase 数值,phase 越低的 lifecycle 越先执行 start 方法。
Map phases = new HashMap<>();
lifecycleBeans.forEach((beanName, bean) -> {
// true:表示只启动 SmartLifecycle 生命周期对象,
// 并且启动 SmartLifecycle对象它的autoStartup是true。
// false :全部启动。
if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
// 获取当前lifecycle对象的 执行排序值。
int phase = getPhase(bean);
// LifecycleGroup 内部存储的都是 phase 值一致的 lifecycle。
LifecycleGroup group = phases.get(phase);
if (group == null) {
group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
phases.put(phase, group);
}
// 将当前lifecycle添加到 当前phase值一致的 group 内。
group.add(beanName, bean);
}
});
//执行到这里,lifecycle就按照phase分完组了
if (!phases.isEmpty()) {
List keys = new ArrayList<>(phases.keySet());
//从小到大的一个排序。
Collections.sort(keys);
for (Integer key : keys) {
//执行 lifecycleGroup.start() 启动分组内的lifecycle。
phases.get(key).start();
}
}
}
DefaultLifecycleProcessor.LifecycleGroup#start
public void start() {
if (this.members.isEmpty()) {
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Starting beans in phase " + this.phase);
}
//排序..
Collections.sort(this.members);
for (LifecycleGroupMember member : this.members) {
doStart(this.lifecycleBeans, member.name, this.autoStartupOnly);
}
}
private void doStart(Map lifecycleBeans, String beanName, boolean autoStartupOnly) {
// 确保lifecycle只被启动一次。 在一个分组内 被启动了,
// 其它分组内,就看不到该lifecycle了。
Lifecycle bean = lifecycleBeans.remove(beanName);
if (bean != null && bean != this) {
// 获取当前即将要被启动的lifecycle所依赖的其它beanName
String[] dependenciesForBean = getBeanFactory().getDependenciesForBean(beanName);
// 先启动当前lifecycle所依赖的lifecycle。
for (String dependency : dependenciesForBean) {
doStart(lifecycleBeans, dependency, autoStartupOnly);
}
// true:表示只启动 SmartLifecycle 生命周期对象,
// 并且启动 SmartLifecycle对象它的autoStartup是true。
// false :全部启动。
if (!bean.isRunning() &&
(!autoStartupOnly || !(bean instanceof SmartLifecycle) || ((SmartLifecycle) bean).isAutoStartup())) {
if (logger.isTraceEnabled()) {
logger.trace("Starting bean '" + beanName + "' of type [" + bean.getClass().getName() + "]");
}
try {
//启动当前lifecycle。
bean.start();
}
catch (Throwable ex) {
throw new ApplicationContextException("Failed to start bean '" + beanName + "'", ex);
}
if (logger.isDebugEnabled()) {
logger.debug("Successfully started bean '" + beanName + "'");
}
}
}
}
9.3 DefaultLifecycleProcessor#stop
public void stop() {
stopBeans();
this.running = false;
}
private void stopBeans() {
// 获取到所有实现了 Lifecycle接口的对象,
// 包装到map内,key是beanName,value 是 lifecycle对象。
Map lifecycleBeans = getLifecycleBeans();
// 因为生命周期对象 可能依赖其它生命周期对象的执行结果,
// 所以需要执行顺序,靠什么实现呢?
// 靠 phase 数值,phase 越低的 lifecycle 越晚执行 stop 方法。
Map phases = new HashMap<>();
lifecycleBeans.forEach((beanName, bean) -> {
int shutdownPhase = getPhase(bean);
LifecycleGroup group = phases.get(shutdownPhase);
if (group == null) {
group = new LifecycleGroup(shutdownPhase, this.timeoutPerShutdownPhase, lifecycleBeans, false);
phases.put(shutdownPhase, group);
}
group.add(beanName, bean);
});
if (!phases.isEmpty()) {
List keys = new ArrayList<>(phases.keySet());
//降序 ,lifecycle 最先启动的,最晚关闭;最晚启动,最先关闭。
keys.sort(Collections.reverseOrder());
for (Integer key : keys) {
phases.get(key).stop();
}
}
}
DefaultLifecycleProcessor.LifecycleGroup#stop
public void stop() {
if (this.members.isEmpty()) {
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Stopping beans in phase " + this.phase);
}
this.members.sort(Collections.reverseOrder());
// 创建了latch,并且设置latch内部的值为 当前分组内 smartLifecycle的数量。
CountDownLatch latch = new CountDownLatch(this.smartMemberCount);
// 保存当前正在处于 关闭ing 的 smartLifecycle beanName。
Set countDownBeanNames = Collections.synchronizedSet(new LinkedHashSet<>());
// bf 全部的lifecycle BeanNames
Set lifecycleBeanNames = new HashSet<>(this.lifecycleBeans.keySet());
// 处理本分组内的需要关闭的 lifecycle。
for (LifecycleGroupMember member : this.members) {
if (lifecycleBeanNames.contains(member.name)) {
doStop(this.lifecycleBeans, member.name, latch, countDownBeanNames);
}
else if (member.bean instanceof SmartLifecycle) {
// Already removed: must have been a dependent bean from another phase
latch.countDown();
}
}
try {
// 关闭分组lifecycle的主线程,会在这里等待,等待latch 归0,或者超时。 30s.
latch.await(this.timeout, TimeUnit.MILLISECONDS);
if (latch.getCount() > 0 && !countDownBeanNames.isEmpty() && logger.isInfoEnabled()) {
logger.info("Failed to shut down " + countDownBeanNames.size() + " bean" +
(countDownBeanNames.size() > 1 ? "s" : "") + " with phase value " +
this.phase + " within timeout of " + this.timeout + "ms: " + countDownBeanNames);
}
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
private void doStop(Map lifecycleBeans, final String beanName,
final CountDownLatch latch, final Set countDownBeanNames) {
Lifecycle bean = lifecycleBeans.remove(beanName);
if (bean != null) {
// 依赖当前lifecycle的其它对象 beanName.
String[] dependentBeans = getBeanFactory().getDependentBeans(beanName);
// 因为当前lifecycle即将要关闭了,所以那些依赖了
// 当前lifecycle的bean,如果也是lifecycle对象的话,也要先于当前对象关闭。
for (String dependentBean : dependentBeans) {
doStop(lifecycleBeans, dependentBean, latch, countDownBeanNames);
}
try {
if (bean.isRunning()) {
if (bean instanceof SmartLifecycle) {
if (logger.isTraceEnabled()) {
logger.trace("Asking bean '" + beanName + "' of type [" +
bean.getClass().getName() + "] to stop");
}
// 将当前SmartLifecycle beanName 添加到
// countDownBeanNames 集合内,该集合表示正在关闭的 smartLifecycle。
countDownBeanNames.add(beanName);
// Smartlifecycle 可以传递一个Callback ,
// 理论上可以支持异步关闭 生命周期 对象了。
((SmartLifecycle) bean).stop(() -> {
latch.countDown();
countDownBeanNames.remove(beanName);
if (logger.isDebugEnabled()) {
logger.debug("Bean '" + beanName + "' completed its stop procedure");
}
});
}
else {
// 普通的lifecycle 对象,直接调用 lifecycle.stop()
if (logger.isTraceEnabled()) {
logger.trace("Stopping bean '" + beanName + "' of type [" +
bean.getClass().getName() + "]");
}
bean.stop();
if (logger.isDebugEnabled()) {
logger.debug("Successfully stopped bean '" + beanName + "'");
}
}
}
else if (bean instanceof SmartLifecycle) {
// Don't wait for beans that aren't running...
latch.countDown();
}
}
catch (Throwable ex) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to stop bean '" + beanName + "'", ex);
}
}
}
}