Spring啓動和Bean建立過程當中的可擴展接口

1.前言

Spring中有一些能夠擴展的接口,能夠用來在工做中更深度的使用Spring,這些接口大多分佈在AbstractApplicationContext.refresh() 和 AbstractAutowireCapableBeanFactory.createBean()這兩個方法的執行過程當中。java

2.AbstractApplicationContext.refresh()

2.1 refresh()簡介

AbstractApplicationContext.refresh()是Spring環境啓動 過程當中的一個重要方法,此方法中實例化了全部的bean,任何ApplicationContext的實現,都須要調用此方法spring

如上圖所示,Spring中,全部的ApplicationContext,都繼承於AbstractApplicationContext。

爲節省篇幅,僅將要分析的幾個方法代碼片斷抽取出來,refresh()的所有實現可查看源碼中的AbstractApplicationContext.refresh()方法。app

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

// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);

// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);

// Initialize event multicaster for this context.
initApplicationEventMulticaster();

// Check for listener beans and register them.
registerListeners();
複製代碼

2.2 prepareRefresh()

調用了initPropertySources,初始化資源,如屬性文件中的佔位符等。 由子類實現,如AbstractRefreshableWebApplicationContext。post

2.3 obtainFreshBeanFactory()

獲取ConfigurableListableBeanFactory:this

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

此方法中主要執行兩部分流程:spa

2.3.1 調用refreshBeanFactory()

調用抽象方法refreshBeanFactory(),由子類AbstractRefreshableApplicationContext實現,代碼片斷以下:debug

DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);  //讀取xml,註冊BeanDefinition。
複製代碼

loadBeanDefinitions是AbstractRefreshableApplicationContext的一個抽象方法,由其子類AbstractXmlApplicationContext實現 ,詳細瞭解AbstractXmlApplicationContext可參考Spring自定義配置的源碼解析與實現3d

2.3.2 調用getBeanFactory()

調用抽象方法getBeanFactory(),由子類AbstractRefreshableApplicationContext實現,返回一個接口ConfigurableListableBeanFactory的實現類DefaultListableBeanFactory的實例。代理

這個DefaultListableBeanFactory實例,由上面的refreshBeanFactory()中調用createBeanFactory()建立。code

2.4 prepareBeanFactory

配置ConfigurableListableBeanFactory。

ConfigurableListableBeanFactory繼承了BeanFactory,實現類是DefaultListableBeanFactory。

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory){....}

2.4.1 設置classLoader:

beanFactory.setBeanClassLoader(getClassLoader());

經過org.springframework.util.ClassUtils.getDefaultClassLoader()獲取ClassLoader。

2.4.2 建立ApplicationContextAwareProcessor

beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

建立ApplicationContextAwareProcessor對象,而且添加到DefaultListableBeanFactory中。

ApplicationContextAwareProcessor實現了BeanPostProcessor,並在實現的BeanPostProcessor.postProcessBeforeInitialization中,定義了對一些列對org.springframework.beans.factory.Aware子接口的處理。

注:這裏只是添加了BeanPostProcessor,但並未執行。

private void invokeAwareInterfaces(Object bean) {
    if (bean instanceof Aware) {
		if (bean instanceof EnvironmentAware) {
			((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
		}
		if (bean instanceof EmbeddedValueResolverAware) {
			((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
		}
		if (bean instanceof ResourceLoaderAware) {
			((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
		}
		if (bean instanceof ApplicationEventPublisherAware) {
			((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
		}
		if (bean instanceof MessageSourceAware) {
			((MessageSourceAware) bean).setMessageSource(this.applicationContext);
		}
		if (bean instanceof ApplicationContextAware) {
			((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
		}
	}
}
複製代碼

在後續建立Bean的流程中,會執行全部的BeanPostProcessor,也就是會執行ApplicationContextAwareProcessor.postProcessBeforeInitialization設置各類Aware接口。

2.4.3 設置默認的上下文bean

註冊Spring自身使用的一些Bean:

// 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());
		}
複製代碼

其中:

String ENVIRONMENT_BEAN_NAME = "environment";
String SYSTEM_PROPERTIES_BEAN_NAME = "systemProperties";
String SYSTEM_ENVIRONMENT_BEAN_NAME = "systemEnvironment";
複製代碼

2.5 invokeBeanFactoryPostProcessors

調用全部的 BeanFactoryPostProcessor.postProcessBeanFactory。 PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors){....}
複製代碼

2.6 registerBeanPostProcessors

註冊全部的BeanPostProcessor

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
	}
複製代碼

2.7 initApplicationEventMulticaster

初始化ApplicationEventMulticaster,實現類是SimpleApplicationEventMulticaster。

this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
複製代碼

public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";

2.8 registerListeners

向ApplicationEventMulticaster註冊ApplicationListner。

/** * Add beans that implement ApplicationListener as listeners. * Doesn't affect other listeners, which can be added without being beans. */
	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!
		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<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
		this.earlyApplicationEvents = null;
		if (earlyEventsToProcess != null) {
			for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
				getApplicationEventMulticaster().multicastEvent(earlyEvent);
			}
		}
	}
複製代碼

3 AbstractAutowireCapableBeanFactory.createBean()

3.1 DefaultListableBeanFactory

如上圖所示, DefaultListableBeanFactory是ListableBeanFactory和BeanDefinitionRegistry的默認實現,是全部BeanFactory的始祖。最終建立bean的,是它的直接父類AbstractAutowireCapableBeanFactory.createBean 。

3.2 createBean

protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {....}

主要執行了兩個方法:

  • Object bean = resolveBeforeInstantiation(beanName, mbdToUse); 執行了InstantiationAwareBeanPostProcessor,這個接口是BeanPostProcessor的子類,接口文檔提到爲內部使用。
  • Object beanInstance = doCreateBean(beanName, mbdToUse, args);

3.3 AbstractAutowireCapableBeanFactory.doCreateBean

3.3.1 createBeanInstance

BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) 主要作了如下工做:

  • Class<?> beanClass = resolveBeanClass(mbd, beanName); 根據beanName加載class;
  • BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd);
  • getInstantiationStrategy().instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner)生成bean實例,InstantiationStrategy默認的實現爲CglibSubclassingInstantiationStrategy;
  • 使用BeanWrapper的實現類BeanWrapperImpl封裝上面實例化的對象;
  • 使用initBeanWrapper(BeanWrapper bw)處理後返回。

3.3.2 populateBean

populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) 根據BeanDefinition爲BeanWrapper封裝的bean代理對象設置屬性值。設置的方式,是建立了BeanDefinitionValueResolver對象,並BeanDefinitionValueResolver.resolveValueIfNecessary實現。resolveValueIfNecessary執行了一系列判斷和遞歸調用,將屬性值填充。

3.3.3 initializeBean

Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd)

  • 1 invokeAwareMethods : 執行 BeanNameAware, BeanClassLoaderAware , BeanFactoryAware

  • 2 applyBeanPostProcessorsBeforeInitialization: 調用了全部BeanPostProcessor的postProcessBeforeInitialization方法。

  • 3 invokeInitMethods:

    • 1)執行 InitializingBean.afterPropertiesSet
    • 2)執行 init-method;
  • 4 applyBeanPostProcessorsAfterInitialization: 執行全部的 BeanPostProcessor 的 postProcessAfterInitialization方法。

3.3.4 registerDisposableBeanIfNecessary

註冊Bean銷燬事件。 protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd)

  • 1 執行 DisposableBean.destroy();
  • 2 執行destroy-method;

4 總結

4.1 **Aware

實現**Aware類的接口,用於獲取到Spring環境中的各類信息或對象:

經常使用的有:

  • ApplicationContextAware:獲取當前的ApplicationContext;
  • BeanNameAware:獲取當前的beanName;
  • BeanClassLoaderAware:獲取當前的ClassLoader;
  • BeanFactoryAware:獲取當前的BeanFactory;
  • ApplicationEventPublisherAware:獲取當前的ApplicationEventPublisher,用於發佈事件;要接收事件的類能夠實現ApplicationListener接口,並實現其中的onApplicationEvent方法。

其餘還有:

  • EnvironmentAware
  • EmbeddedValueResolverAware
  • ResourceLoaderAware
  • MessageSourceAware

用於其餘各類Spring上下文信息的獲取。

使用:Bean類實現**Aware接口。

4.2 BeanFactoryPostProcessor

容器實例化任何其它bean以前讀取配置元數據,並能夠根據須要進行修改。

BeanFactoryPostProcessor只定義了一個方法:postProcessBeanFactory(ConfigurableListableBeanFactory)

在全部bean的定義已經加載,可是尚未初始化bean的時候,Spring容器會調用此方法,並能夠根據須要修改ConfigurableListableBeanFactory的內容,如如PropertySourcesPlaceholderConfigurer。

使用:Bean類實現BeanFactoryPostProcessor接口,或調用AbstractApplicationContext.addBeanFactoryPostProcessor添加。

4.3 ApplicationListener

接收ApplicationEventMulticaster廣播的事件,事件是ApplicationEvent及其子類。

接收的是ApplicationEventPublisher發佈的事件。

使用:Bean類實現ApplicationListener接口並實現其定義的方法onApplicationEvent(E event),或調用AbstractApplicaitonContext.addApplicationListener添加。

4.4 BeanPostProcessor

有兩個方法,分別在InitializingBean先後執行,對bean對象進行處理。

  • postProcessBeforeInitialization :在InitializingBean和init-method前執行;
  • postProcessAfterInitialization:在InitializingBean和init-method後執行;

注:不能返回null,不然程序將再也不往下進行。如不須要處理則返回原對象便可。

使用:Bean類實現BeanPostProcessor接口,或調用AbstractBeanFactory. addBeanPostProcessor添加。

4.5 InitializingBean

在bean的各類屬性設置完成後執行,用於執行自定義的初始化操做。

  • 執行 InitializingBean.afterPropertiesSet;
  • 在init-method以前執行;

使用:Bean類實現InitializingBean接口。

4.6 DisposableBean

在bean銷燬以前執行,用於執行銷燬前的操做。

  • 執行 DisposableBean.destroy();
  • 在destroy-method以前執行;

使用:Bean類實現DisposableBean接口。

相關文章
相關標籤/搜索