Spring中有一些能夠擴展的接口,能夠用來在工做中更深度的使用Spring,這些接口大多分佈在AbstractApplicationContext.refresh() 和 AbstractAutowireCapableBeanFactory.createBean()這兩個方法的執行過程當中。java
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();
複製代碼
調用了initPropertySources,初始化資源,如屬性文件中的佔位符等。 由子類實現,如AbstractRefreshableWebApplicationContext。post
獲取ConfigurableListableBeanFactory:this
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
複製代碼
此方法中主要執行兩部分流程:spa
調用抽象方法refreshBeanFactory(),由子類AbstractRefreshableApplicationContext實現,代碼片斷以下:debug
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory); //讀取xml,註冊BeanDefinition。
複製代碼
loadBeanDefinitions是AbstractRefreshableApplicationContext的一個抽象方法,由其子類AbstractXmlApplicationContext實現 ,詳細瞭解AbstractXmlApplicationContext可參考Spring自定義配置的源碼解析與實現3d
調用抽象方法getBeanFactory(),由子類AbstractRefreshableApplicationContext實現,返回一個接口ConfigurableListableBeanFactory的實現類DefaultListableBeanFactory的實例。代理
這個DefaultListableBeanFactory實例,由上面的refreshBeanFactory()中調用createBeanFactory()建立。code
配置ConfigurableListableBeanFactory。
ConfigurableListableBeanFactory繼承了BeanFactory,實現類是DefaultListableBeanFactory。
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory){....}
beanFactory.setBeanClassLoader(getClassLoader());
經過org.springframework.util.ClassUtils.getDefaultClassLoader()獲取ClassLoader。
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接口。
註冊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";
複製代碼
調用全部的 BeanFactoryPostProcessor.postProcessBeanFactory。 PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors){....}
複製代碼
註冊全部的BeanPostProcessor
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
複製代碼
初始化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";
向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);
}
}
}
複製代碼
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {....}
主要執行了兩個方法:
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
執行了InstantiationAwareBeanPostProcessor,這個接口是BeanPostProcessor的子類,接口文檔提到爲內部使用。Object beanInstance = doCreateBean(beanName, mbdToUse, args);
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;populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw)
根據BeanDefinition爲BeanWrapper封裝的bean代理對象設置屬性值。設置的方式,是建立了BeanDefinitionValueResolver對象,並BeanDefinitionValueResolver.resolveValueIfNecessary實現。resolveValueIfNecessary執行了一系列判斷和遞歸調用,將屬性值填充。
Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd)
1 invokeAwareMethods : 執行 BeanNameAware, BeanClassLoaderAware , BeanFactoryAware
2 applyBeanPostProcessorsBeforeInitialization: 調用了全部BeanPostProcessor的postProcessBeforeInitialization方法。
3 invokeInitMethods:
4 applyBeanPostProcessorsAfterInitialization: 執行全部的 BeanPostProcessor 的 postProcessAfterInitialization方法。
註冊Bean銷燬事件。 protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd)
實現**Aware類的接口,用於獲取到Spring環境中的各類信息或對象:
經常使用的有:
其餘還有:
用於其餘各類Spring上下文信息的獲取。
使用:Bean類實現**Aware接口。
容器實例化任何其它bean以前讀取配置元數據,並能夠根據須要進行修改。
BeanFactoryPostProcessor只定義了一個方法:postProcessBeanFactory(ConfigurableListableBeanFactory)。
在全部bean的定義已經加載,可是尚未初始化bean的時候,Spring容器會調用此方法,並能夠根據須要修改ConfigurableListableBeanFactory的內容,如如PropertySourcesPlaceholderConfigurer。
使用:Bean類實現BeanFactoryPostProcessor接口,或調用AbstractApplicationContext.addBeanFactoryPostProcessor添加。
接收ApplicationEventMulticaster廣播的事件,事件是ApplicationEvent及其子類。
接收的是ApplicationEventPublisher發佈的事件。
使用:Bean類實現ApplicationListener接口並實現其定義的方法onApplicationEvent(E event),或調用AbstractApplicaitonContext.addApplicationListener添加。
有兩個方法,分別在InitializingBean先後執行,對bean對象進行處理。
注:不能返回null,不然程序將再也不往下進行。如不須要處理則返回原對象便可。
使用:Bean類實現BeanPostProcessor接口,或調用AbstractBeanFactory. addBeanPostProcessor添加。
在bean的各類屬性設置完成後執行,用於執行自定義的初始化操做。
使用:Bean類實現InitializingBean接口。
在bean銷燬以前執行,用於執行銷燬前的操做。
使用:Bean類實現DisposableBean接口。