spring学习(三)ConfigurableApplicationContext的refresh方法

spring在加载bean的时候,执行的主要方法就是ConfigurableApplicationContext的refresh方法。这个方法在实现类AbstractApplicationContext里做了处理,这里就简单说明一下这个处理方法,下图是我简单画的类关系图


spring学习(三)ConfigurableApplicationContext的refresh方法_第1张图片

这个是类AbstractApplicationContext实现的代码,以下对每个执行进行说明

	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) {
				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}
		}
	}

一、prepareRefresh

此方法主要记录一下开始初始化的时候或active的标记,并对一些properties进行初始化

initPropertySources();//子类实现

getEnvironment().validateRequiredProperties();//如果没有设置Environment取默认的实现StandardEnvironment

二、ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory()

	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		refreshBeanFactory();
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (logger.isDebugEnabled()) {
			logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
		}
		return beanFactory;
	}

此方法全部由子类实现,

在AbstractRefreshApplicationContext实现了refreshBeanFactory方法,此方法最主要的就是loadBeanDefinitions(beanFactory),由子类去实现load所有的beanDefinition,下一次将具体说明这个方法

@Override
	protected final void refreshBeanFactory() throws BeansException {
		if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			customizeBeanFactory(beanFactory);
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}
//创建一个默认的BeanFactory。使用了DefaultListableBeanFactory
protected DefaultListableBeanFactory createBeanFactory() {
		return new DefaultListableBeanFactory(getInternalParentBeanFactory());
	}
spring学习(三)ConfigurableApplicationContext的refresh方法_第2张图片 spring学习(三)ConfigurableApplicationContext的refresh方法_第3张图片
	@Override
	public final ConfigurableListableBeanFactory getBeanFactory() {
		synchronized (this.beanFactoryMonitor) {
			if (this.beanFactory == null) {
				throw new IllegalStateException("BeanFactory not initialized or already closed - " +
						"call 'refresh' before accessing beans via the ApplicationContext");
			}
			return this.beanFactory;
		}
	}

三、prepareBeanFactory(beanFactory);

预处理beanFactory容器,配置一些beanFactory的classLoader和post-processor等

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// Tell the internal bean factory to use the context's class loader etc.
		beanFactory.setBeanClassLoader(getClassLoader());
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver());
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		// Configure the bean factory with context callbacks.
		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
		beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
		beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
		beanFactory.ignoreDependencyInterface(EnvironmentAware.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);

		// 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());
		}
	}

四、postProcessBeanFactory(beanFactory);

此方法由子类执行beanFactory 之前的操作


五、invokeBeanFactoryPostProcessors(beanFactory);

用于执行BeanFactoryPostProcessors中的postProcessBeanFactory,beanFactoryPostProcessor是优先于BeanPostProcessor执行

先执行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry。再执行BeanFactoryPostProcessor.postProcessBeanFactory


spring学习(三)ConfigurableApplicationContext的refresh方法_第4张图片


小例子,此时在加载spring容器时,会打印出当前的Singlecount,注。此时还没有加载指定的业务bean.除非调用getBean(beanName),否则要等到后一步才加载执行

public class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

	@Override
	public void postProcessBeanFactory(
			ConfigurableListableBeanFactory beanFactory) throws BeansException {
		System.out.println(" signleton count :" + beanFactory.getSingletonCount());
	}

}


mybatis与spring集成时,就是配置了一个BeanDefinitionRegistryPostProcessor。并在postProcessBeanDefinitionRegistry这个方法里进行查找mybatis所有配置的mapper

     
       
       
    

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
    if (this.processPropertyPlaceHolders) {
      processPropertyPlaceHolders();
    }

    ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
    scanner.setAddToConfig(this.addToConfig);
    scanner.setAnnotationClass(this.annotationClass);
    scanner.setMarkerInterface(this.markerInterface);
    scanner.setSqlSessionFactory(this.sqlSessionFactory);
    scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
    scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
    scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
    scanner.setResourceLoader(this.applicationContext);
    scanner.setBeanNameGenerator(this.nameGenerator);
    scanner.registerFilters();
    scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
  }




六、registerBeanPostProcessors(beanFactory);

注册beanPostProcessor,注意要和beanFactoryPostProcessor区分开,beanFactoryPostProcessor是执行。此时的这里只是注册beanPostProcessor,beanFactoryPostProcessor优先于beanPostProcessor执行

beanPostProcessor的流程与beanFactoryPostProcessor执行流程类似。

1、先查找所有BeanPostProcessor类型的bean

2、注册属于PriorityOrdered的beanPostProcessor

3、注册属于Ordered类型的beanPostProcessor

4、注册剩余的beanPostProcessor

5、增加一个继承了ApplicationListener的beanPostProcessor检查ApplicationListenerDetector


public class TestBeanPostProcessor implements BeanPostProcessor {

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		System.out.println("before beanName [" + beanName + "] bean class [" + bean.getClass() + "]");
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		System.out.println("after beanName [" + beanName + "] bean class [" + bean.getClass() + "]");
		return bean;
	}

}


七、initMessageSource();

初始化一个messageSource类

1、判断beanFactory是否有name=messageSource的MessageSource

2、生成一个默认的MessageSource  DelegatingMessageSource并注册到beanFactory中

八、initApplicationEventMulticaster();

初始化ApplicationEvent类

1、判断beanFactory是否有name =applicationEventMulticaster的ApplicationEventMulticaster

2、生成默认的SimpleApplicationEventMulticaster 并注册到beanFactory中

九、onRefresh();

此方法由子类实现

十、registerListeners();

加载所以ApplicationListener并注册到ApplicationEventMulticaster中

十一、finishBeanFactoryInitialization(beanFactory);

处理beanFactory初始化结束的操作

其中

beanFactory.preInstantiateSingletons();

开始实例化所有未实例化的bean

十二、finishRefresh()

protected void finishRefresh() {
		// 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);
	}

1、生成一个LifecycleProcessor.默认为DefaultLifecycleProcessor

2、执行LiftcycleProcessor的onfresh方法,执行所有属于Lifecycle的bean

3、推送ApplicationEvent


你可能感兴趣的:(spring)