Spring容器初始化到销毁这部分的代码,主要就是指refresh()方法
@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.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
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.
onRefresh();
// Check for listener beans and register them.
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...
resetCommonCaches();
}
}
}
这部分代码按照我的学习逻辑主要分为三个部分
- beanFactory的的创建及预准备工作(标准初始化)
- 初始化bean之前的其他资源初始化
- 实例化所有剩余的(非lazy-init)单例
接下来我就按照这三部分逻辑来分别梳理refresh()的逻辑
1. beanFactory的的创建及预准备工作(标准初始化)
1.1 prepareRefresh()
刷新的预处理
AnnotationConfigReactiveWebServerApplicationContext
protected void prepareRefresh() {
this.scanner.clearCache();//清理缓存
super.prepareRefresh();//准备刷新
}
1.1.1 prepareRefresh()
protected void prepareRefresh() {
// 省略若干代码
// 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<>();
}
1.1.2 prepareRefresh()
protected void prepareRefresh() {
// 省略若干代码
// 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<>();
}
1.1.3 initPropertySources()
/**
* <p>Replace any stub property sources with actual instances.
* @see org.springframework.core.env.PropertySource.StubPropertySource
* @see org.springframework.web.context.support.WebApplicationContextUtils#initServletPropertySources
*/
protected void initPropertySources() {
// For subclasses: do nothing by default.
}
初始化一些属性设置,子类自定义个性化的属性设置方法。
1.1.4 getEnvironment().validateRequiredProperties();
对自定义属性进行校验
1.1.4 this.earlyApplicationEvents = new LinkedHashSet<>();
保存容器早期事件
1.2 obtainFreshBeanFactory()
获取BeanFactory
/**
* 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()
/**
* 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
*/
@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");
}
//注意此时beanFactory登场了
this.beanFactory.setSerializationId(getId());
}
为beanFactory赋予id标识
notice
此时beanFactory登场了
refreshBeanFactory方法是AbstractApplicationContext中定义的一个抽象方法
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
在子类GenericApplicationContext中进行了逻辑重写
image.png
可以发现beanFactory是其中的一个成员变量
在实例化GenericApplicationContext对象的时候对该变量进行赋值
/**
* Return the single internal BeanFactory held by this context
* (as ConfigurableListableBeanFactory).
*/
@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
return this.beanFactory;
}
1.3 prepareBeanFactory(beanFactory)
beanFactory的预准备工作,对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.
//todo 1. 设置BeanFactory的类加载器,支持表达是解析器
beanFactory.setBeanClassLoader(getClassLoader());
if (!shouldIgnoreSpel) {
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
}
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
//todo 2. 添加PostProcessor (ApplicationContextAwareProcessor)
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//todo 3. 忽略 一些自动装配的接口,防止他们自动注入
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.ignoreDependencyInterface(ApplicationStartup.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
// todo 4. 添加可以解析的自动装配,这些自动装配到beanFactory中的实例我们可以直接通过 @Autowired注解获取实例 其他组件中可以直接使用
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.
//todo 5. 添加BeanPostProcessor(ApplicationListenerDetector)
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
//todo 6. 添加AspectJ相关的组件
if (!IN_NATIVE_IMAGE && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
//todo 7. 给beanFactory添加一些默认组件:environment【ConfigurableEnvironment】,systemProperties【Map<String, Object>】,systemEnvironment【Map<String, Object>】,
//applicationStartup【ApplicationStartup】
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());
}
}
1.4 postProcessBeanFactory(beanFactory)
在beanFactory准备工作完成后进行的后置处理工作
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
交给子类进行自己的逻辑扩展用
交给客户端扩展用的接口
总结
以上就是beanFactory的预准备工作,在预备工作中完成了如下工作:
1.prepareRefresh():刷新的预处理:
初始化自定义属性,并对之校验
初始化容器的早期事件
2.obtainFreshBeanFactory():为beanFactory赋予id,并获取这个beanFactory
3.prepareBeanFactory():beanFactory的预准备工作:
设置类的加载器
设置一些需要忽略可以自动装配的接口
注册一些可以自动装配的依赖
设置一些后置处理器
注册一些单例组件
4.postProcessBeanFactory():beanFactory准备工作完成后的后置处理器,对客户端开放,添加逻辑。
2. 初始化bean之前的其他资源初始化
2.1 invokeBeanFactoryPostProcessors(beanFactory)
执行BeanFactoryPostProcessors
BeanFactoryPostProcessors: BeanFactory的后置处理器,在beanFactory标准初始化之后执行。
/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before singleton instantiation.
*/
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 (!IN_NATIVE_IMAGE && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
getBeanFactoryPostProcessors() <AbstractApplicationContext>
/**
* Return the list of BeanFactoryPostProcessors that will get applied
* to the internal BeanFactory.
*/
public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
return this.beanFactoryPostProcessors;
}
2.1.1 beanFactoryPostProcessors接口
@FunctionalInterface
public interface BeanFactoryPostProcessor {
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for overriding or adding
* properties even to eager-initializing beans.
* @param beanFactory the bean factory used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
BeanFactoryPostProcessor和他的子接口BeanDefinitionRegistryPostProcessor
/**
* Extension to the standard {@link BeanFactoryPostProcessor} SPI, allowing for
* the registration of further bean definitions <i>before</i> regular
* BeanFactoryPostProcessor detection kicks in. In particular,
* BeanDefinitionRegistryPostProcessor may register further bean definitions
* which in turn define BeanFactoryPostProcessor instances.
*
* @author Juergen Hoeller
* @since 3.0.1
* @see org.springframework.context.annotation.ConfigurationClassPostProcessor
*/
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
/**
* Modify the application context's internal bean definition registry after its
* standard initialization. All regular bean definitions will have been loaded,
* but no beans will have been instantiated yet. This allows for adding further
* bean definitions before the next post-processing phase kicks in.
* @param registry the bean definition registry used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}
2.1.2 PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors())
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
//存放BeanDefine的集合
Set<String> processedBeans = new HashSet<>();
//@1 先判断是否为BeanDefinitionRegistry,因为beanFactory是DefaultListableBeanFactory,是BeanDefinitionRegistry的实现类肯定满足条件
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
//@2 定义两个BeanFactoryPostProcessor,BeanDefinitionRegistryPostProcessor类型的集合
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
//正常这个beanFactoryPostProcessors集合一般情况下都是空的,除非我们手动调用容器的addBeanFactoryPostProcessor方法
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
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.
//临时变量用来存储BeanDefinitionRegistryPostProcessor集合,对BeanDefinitionRegistryPostProcessor会有三段操作逻辑,为了避免重复创建这个集合,用这个临时变量来存储每段逻辑的变量值,并在最后清空。
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
//@3 筛选PriorityOrdered类型的Bean,并对之进行排序,和注册
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
//@3.1 晒选所有实现PriorityOrdered接口的BeanDefine,并放到currentRegistryProcessors集合中,和processedBeans集合中
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
//@3.2 根据ordered接口进行排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
//@3.3 将实现PriorityOrdered接口的BeanDefine集合赋值给registryProcessors集合
registryProcessors.addAll(currentRegistryProcessors);
//@3.4 执行BeanDefinitionRegistryPostProcessor 的BeanDefinitionRegistryPostProcessors方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
//@3.5 清空临时变量
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
//@4 逻辑和上面一样,筛选Ordered类型BeanDefine,然后排序,注册。
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
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, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
//@5 对没有实现PriorityOrdered和Ordered的BeanDefine,进行筛选,排序,注册
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, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
//@6 这里开始执行单独实现了BeanFactoryPostProcessor接口的后置处理器
//先执行实现了BeanDefinitionRegistryPostProcessor的BeanFactoryPostProcessor,在前面的逻辑中只执行了BeanDefinitionRegistryPostProcessor特有的postProcessBeanDefinitionRegistry方法,它的postProcessBeanFactory方法还没有被执行,它会在这里被执行
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
//执行直接实现了BeanFactoryPostProcessor接口的后置处理器
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
}
这段代码逻辑我之前的文章中介绍过,主要做了如下两方面工作:
1.BeanDefine的扫描,解析,注册
通过BeanDefinitionRegistryPostProcessor接口的
postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
方法,完成外置配置和内置配置的扫描和解析成beanDefine,并注册到BeanFactory(DefaultListableBeanFactory容器) 中。
notice:
此时的BeanDefine中的属性值为
"${demo.constant.user.age}"
这类占位符
2.BeanDefine配置的加载,解析,并将BeanDefine中的展位符替换成实际配置中的值
通过beanFactoryPostProcessors接口的
postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
方法,完成beanDefine 属性的解析,即将占位符替换成实际值。
2.2 registerBeanPostProcessors(beanFactory);
/**
* Instantiate and register all BeanPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before any instantiation of application beans.
*/
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
注册BeanPostProcessors,bean的后置处理器,拦截bean的创建过程,但是并不执行这些处理器
2.2.1 BeanPostProcessors接口
BeanPostProcessors的子接口:
DestructionAwareBeanPostProcessor
InstantiationAwareBeanPostProcessor
SmartInstantiationAwareBeanPostProcesso
父接口InstantiationAwareBeanPostProcessor
MergedBeanDefinitionPostProcessor
以上这些BeanPostProcessors的子接口,在Bean创建后的执行时间不同
2.2.2 registerBeanPostProcessors(beanFactory, this)
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
//获取所有的BeanPostProcessor
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
//省略若干代码
//todo @1 First, register the BeanPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
//将 priorityOrderedPostProcessors类型的BeanPostProcessors注册到beanFactory
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// todo @2 Next, register the BeanPostProcessors that implement Ordered.
//将 ordered类型的BeanPostProcessors注册到beanFactory
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// todo @3 Now, register all regular BeanPostProcessors.
//将没有实现任何priorityOrderedPostProcessors和orderedPostProcessors的 BeanPostProcessors注册到beanFactory
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
//todo @4 Finally, re-register all internal BeanPostProcessors.
//最后注册internalPostProcessors<MergedBeanDefinitionPostProcessor>
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
//todo @5 Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
//注册BeanPostProcessor<ApplicationListenerDetector> 用来检查注册到beanFactory中的bean哪些是监听器
//如果是监听器则将这个bean放入容器中保存 this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
2.3 initMessageSource()
初始化MessageSource组件用于:国际化,消息绑定,解析
2.4 initApplicationEventMulticaster()
初始化事件派发器
2.5 onRefresh()
留给客户端重写Refresh方法,在容器刷新的时候可以自定义逻辑。
registerListeners()
注册项目中的监听器
1.从容器中获取ApplicationListener
2.将每个监听器添加到事件派发器中
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
3.派发之前步骤产生的事件
总结:
以上就是初始化bean之前的其他资源初始化过程,完成了如下工作:
1.invokeBeanFactoryPostProcessors(beanFactory):执行BeanFactoryPostProcessor的方法:
BeanFactoryPostProcessor:
postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)方法,完成外置配置和内置配置的扫描和解析成beanDefine,并注册到BeanFactory(DefaultListableBeanFactory容器) 中。
BeanDefinitionRegistryPostProcessor:
postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) 方法,完成beanDefine 属性的解析,即将占位符替换成实际值。
2.registerBeanPostProcessors(beanFactory):注册BeanPostProcessor(Bean的后置处理器)
3.initMessageSource():初始化MessageSource组件(做国际化功能;消息绑定,消息解析)
4.initApplicationEventMulticaster():初始化事件派发器
5.onRefresh():留给客户端重写Refresh方法,在容器刷新的时候可以自定义逻辑
3. 实例化所有剩余的(非lazy-init)单例
3.1 finishBeanFactoryInitialization(beanFactory);
初始化所有剩下的单实例bean,完成bean工厂的初始化
/**
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
//忽略若干代码
// Instantiate all remaining (non-lazy-init) singletons.
//实例化所有剩余的(非lazy-init)单例
beanFactory.preInstantiateSingletons();
}
3.1.1 beanFactory.preInstantiateSingletons();
初始化后剩下的费非加载单实例bean
@Override
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<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
//触发所有非惰性单例bean的初始化
for (String beanName : beanNames) {
//通过beanName获取BeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//bean不是抽象的,单实例, 非懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//判断bean是不是FactoryBean(判断这个bean是否实现FactoryBean接口),主要是判断下面逻辑是通过FactoryBean获取bean还是通过getBean(beanName)获取
if (isFactoryBean(beanName)) {
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<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
//获取像客户端通过注解装配的bean而不是通过实现FactoryBean doGetBean(name, null, null, false) 我们重点来看这个没有实现FactoryBean接口的bean的获取
getBean(beanName);
}
}
}
}
此时的beanNames
image.png
3.1.2 getBean(String name)
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
3.1.3 doGetBean(name, null, null, false);
/**
* Return an instance, which may be shared or independent, of the specified bean.
* @param name the name of the bean to retrieve
* @param requiredType the required type of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @param typeCheckOnly whether the instance is obtained for a type check,
* not for actual use
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
@SuppressWarnings("unchecked")
protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
// todo @1. 先获取缓存中保存的单实例Bean。如果能获取到说明这个Bean之前被创建过(所有创建过的单实例Bean都会被缓存起来)
//从private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);获取的
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
//省略若干
// typeCheckOnly 这里是doGetBean传入的参数,为false doGetBean(name, null, null, false)
if (!typeCheckOnly) {
//todo @2 标记该Bean处于创建状态
markBeanAsCreated(beanName);
}
StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
.tag("beanName", name);
try {
if (requiredType != null) {
beanCreation.tag("beanType", requiredType::toString);
}
//todo 3. 根据Bean的名称找到BeanDefinition
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
// todo 4. 获取当前Bean依赖的其他Bean;如果有按照getBean()把依赖的Bean先创建出来
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
// todo 5. 创建单实例bean
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
//省略若干
return (T) bean;
}
3.1.3 createBean(beanName, mbd, args);
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
//省略若干
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
//在解析bean之前先实例化 InstantiationAwareBeanPostProcessor 接口的bean 先触发:postProcessBeforeInstantiation();
////如果有返回值:触发postProcessAfterInitialization();
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
try {
//如果前面的InstantiationAwareBeanPostProcessor没有返回代理对象 创建bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
}
3.1.4 doCreateBean(beanName, mbdToUse, args);
bean的实例化,属性注入,初始化,销毁都是在这个方法中注册的
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
//省略若干
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (instanceWrapper == null) {
//todo1. 利用工厂方法或者对象的构造器创建出Bean实例
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
//todo2. Bean属性赋值
populateBean(beanName, mbd, instanceWrapper);
//todo3. Bean初始化
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
// Register bean as disposable.
//todo 4. 注册Bean的销毁方法
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
}
instanceWrapper = createBeanInstance(beanName, mbd, args);
image.png
exposedObject = initializeBean(beanName, exposedObject, mbd);
image.png
3.2 finishRefresh();
完成BeanFactory的初始化创建工作;IOC容器就创建完成
此时的beanFactory
image.png
image.png
第三部分逻辑总结
实例化所有剩余的(非lazy-init)单例
- finishBeanFactoryInitialization(beanFactory):初始化所有剩下的单实例bean;
1.createBeanInstance(beanName, mbd, args):实例化bean
选择一个实例化策略去实例化bean。默认使用CglibSubclassingInstantiationStrategy。该策略模式中,首先判断bean是否有方法被覆盖,如果没有则直接通过反射的方式来创建,如果有的话则通过CGLIB来实例化bean对象. 把创建好的bean对象包裹在BeanWrapper里。
2.populateBean(beanName, mbd, instanceWrapper):属性赋值
3.initializeBean(beanName, exposedObject, mbd):初始化
这个初始化我的理解是为了留给客户端的,留给客户端对实例化之后的bean进行再次定义,来看看他的初始化流程:
3.1 如果这个Bean实现了BeanNameAware接口,会调用它实现的setBeanName,让bean可以获取他当前bean的名字
3.2 如果这个Bean实现了BeanFactoryAware接口,会调用它实现的setBeanFactory(),会使当前bean获取spring的BeanFactory
3.3 如果这个Bean实现了ApplicationContextAware接口,会调用setApplicationContext(ApplicationContext)方法,和上一步一样,获取- - spring的上下文信息,但是获取的信息比上一步多,因为ApplicationContext是BeanFactory的子接口,有更多的实现方法
3.4 如果这个Bean关联了BeanPostProcessor接口,将会调用postProcessBeforeInitialization(Object obj, String s)方法,BeanPostProcessor经常被用作是Bean内容的更改,并且由于这个是在Bean初始化结束时调用After方法,也可用于内存或缓存技术
3.5 如果这个Bean在Spring配置文件中配置了init-method属性,则当前bean按照该初始化方法中定义的逻辑对bean实例进行自定义
3.6 如果这个Bean关联了BeanPostProcessor接口,将会调用postAfterInitialization(Object obj, String s)方法
3.7 如果这个Bean在Spring配置文件中配置了destroyMethod属性,则当前bean按照指定的销毁方法进行销毁 - registerDisposableBeanIfNecessary(beanName, bean, mbd)
finishRefresh();完成BeanFactory的初始化创建工作;IOC容器就创建完成
notice:
后置处理器
springv中每一个bean创建完成,都会使用各种后置处理器进行处理;来增强bean的功能
常见的后置处理器
n1.InstantiationAwareBeanPostProcessor
围绕着bean的初始化之前和之后运行(这里的初始化指围绕在createBeanInstance执行前和initializeBean执行后)
【InstantiationAwareBeanPostProcessor接口】调用InstantiationAwareBeanPostProcessor接口的postProcessBeforeInstantiation方法,实例化前,beanName======》studentBean
【Bean构造方法】学生类的无参构造方法
【InstantiationAwareBeanPostProcessor接口】调用InstantiationAwareBeanPostProcessor接口的postProcessPropertyValues方法
【BeanNameAware接口】调用BeanNameAware的setBeanName方法得到Bean的名称====>studentBean
【BeanFactoryAware接口】调用BeanFactoryAware的setBeanFactory方法得到beanFactory引用
【ApplicationContext接口】调用ApplicationContext的setApplicationContext方法得到Spring上下文
【BeanPostProcessor接口】调用postProcessBeforeInitialization方法,这里可对studentBean的属性进行更改。
【init-method】调用init-method属性配置的初始化方法
【InitializingBean接口】调用InitializingBean接口的afterPropertiesSet方法
【BeanPostProcessor接口】调用postProcessAfterInitialization方法,这里可对studentBean的属性进行更改。
【InstantiationAwareBeanPostProcessor接口】调用InstantiationAwareBeanPostProcessor接口的postProcessAfterInitialization方法,实例化后,beanName========》studentBean
【DisposableBean接口】调用DisposableBean接口的destroy方法
n2.BeanPostProcessor
这个后置处理器围绕在bean init-method前后执行
n3.BeanFactoryPostProcessor
BeanFactory的后置处理器,源码中用来完成beanDfine的扫描,解析,注册
n4. xxxAware
Aware类型的接口的作用就是获取spring中的某些资源,基本都能够见名知意,xxxAware就代表获取什么样的资源,比如BeanFactoryAware,就可以拿到spring的容器BeanFactory
网友评论