当前位置: 代码迷 >> 综合 >> spring启动流程探索二、refresh()(1)
  详细解决方案

spring启动流程探索二、refresh()(1)

热度:38   发布时间:2023-11-26 12:05:50.0

spring探索第二节

  • refresh()
    • prepareRefresh()
    • obtainFreshBeanFactory
      • refreshBeanFactory
    • prepareBeanFactory(beanFactory)
      • registerSingleton(String beanName, Object singletonObject)
        • updateManualSingletonNames()
        • super.registerSingleton(beanName, singletonObject);
          • addSingleton(beanName, singletonObject);

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.// 告诉子类刷新内部 bean factoryConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// Prepare the bean factory for use in this context.// 在上下文中 准备beanFactoryprepareBeanFactory(beanFactory);try {
    // Allows post-processing of the bean factory in context subclasses.// 处理在beanfactory 的postProcess// 主要是提供给三方框架来扩展的postProcessBeanFactory(beanFactory);// 调用工厂处理器注册beans到上下文// Invoke factory processors registered as beans in the context.// 处理beanFactory内部的beanFactoryPostProcessors// 然后处理注册在beanFactory 的BeanDefinitionRegistryPostProcessor// 按PriorityOrdered >Ordered>none的顺序执行postProcessBeanDefinitionRegistry方法// 再执行postProcessBeanFactory方法//2. 处理注册再beanFactory 的BeanFactoryPostProcessor// 按PriorityOrdered >Ordered>none的顺序执行postProcessBeanFactory// 清除缓冲 todo 未细看invokeBeanFactoryPostProcessors(beanFactory);// 按PriorityOrdered >Ordered>none按PriorityOrdered >Ordered>none// 注册 bean processors// 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.// 实例化bean 单例的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();}}}

refresh这个方法里面涉及的类和方法多而杂,如果突然一下子去看的话特别容易被劝退,所以我们一次性不讲很多,大家可以跟我一起慢慢学。先来个简单的提提神

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#setRequiredPropertiesgetEnvironment().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<>();}

其实看这个类名就能知道意思,刷新前的准备,那这个类就是做一些准备工作,准备上下文刷新,设置启动时间,和存活标志,加载资源

obtainFreshBeanFactory

	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    refreshBeanFactory();return getBeanFactory();}

refreshBeanFactory

	@Overrideprotected final void refreshBeanFactory() throws IllegalStateException {
    // 查看context上下问是否刷新中if (!this.refreshed.compareAndSet(false, true)) {
    throw new IllegalStateException("GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");}// 设置一个序列idthis.beanFactory.setSerializationId(getId());}

这个方法也很简单,就是看看context 是否在创建,然后给beanFactory设置一个唯一id

prepareBeanFactory(beanFactory)

好了 兄弟们,第一个大家伙来了,这个方法要做的工作有很多,具体的一些我写在代码注释里

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // Tell the internal bean factory to use the context's class loader etc.// 告诉内部bean factory 使用上下文的class loadbeanFactory.setBeanClassLoader(getClassLoader());// 设置el 表达式的解析器beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));// Configure the bean factory with context callbacks.// 忽略一些接口的自动装配EnvironmentAware,// EmbeddedValueResolverAware,// ResourceLoaderAware//ApplicationEventPublisherAwarebeanFactory.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.// 注册一些自动装配的类 (往这个集合中resolvableDependencies)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.// 注册初期的ApplicationListenerDetector监听器侦测器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.// 注册一些默认的environment beansif (!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());}}

这里面涉及到beanFactory.registerSingleton方法,这个方法其实开始不打算在这里讲的,但是想了想还是在这讲,先给大家留个印象。

registerSingleton(String beanName, Object singletonObject)

	@Overridepublic void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
    // 注册给定的singletonObjectsuper.registerSingleton(beanName, singletonObject);// 更新manualSingletonNamesupdateManualSingletonNames(set -> set.add(beanName), set -> !this.beanDefinitionMap.containsKey(beanName));clearByTypeCache();}

updateManualSingletonNames()

private void updateManualSingletonNames(Consumer<Set<String>> action, Predicate<Set<String>> condition) {
    if (hasBeanCreationStarted()) {
    // Cannot modify startup-time collection elements anymore (for stable iteration)synchronized (this.beanDefinitionMap) {
    if (condition.test(this.manualSingletonNames)) {
    Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);action.accept(updatedSingletons);this.manualSingletonNames = updatedSingletons;}}}else {
    // Still in startup registration phaseif (condition.test(this.manualSingletonNames)) {
    action.accept(this.manualSingletonNames);}}}

super.registerSingleton(beanName, singletonObject);

@Overridepublic 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);}}
addSingleton(beanName, singletonObject);
	protected void addSingleton(String beanName, Object singletonObject) {
    synchronized (this.singletonObjects) {
    // singletonObjects 单例池,一级缓存this.singletonObjects.put(beanName, singletonObject);// singletonObjects 单例工厂,三级级缓存this.singletonFactories.remove(beanName);// singletonObjects 早期单例池,二级级缓存this.earlySingletonObjects.remove(beanName);// 已经注册的单例this.registeredSingletons.add(beanName);}}

prepareBeanFactory的方法主要是做了以下内容:
取消一些类的自动装配
更新了一些类的自动装配
注册一些默认environment bean
postProcessBeanFactory(beanFactory)是一个扩展接口,spring内部并没有对他实现,所以就没啥好讲的
invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory)这个方法内容太多了。我打算拿出单独的一章节来讲。可能有的小伙伴看到我写的东西杂,而且贴的代码很多,不大愿意看了。我还是劝下大家 耐心看看,学习源码就是这样,只要了解了refresh这个方法,spring中很多东西就很容易看明白了,后面去讲spring的架构也更容易理解。
最后谢谢大家的观看,点点赞,我会给大家带来更多的源码解析。

  相关解决方案