先來看下ClassPathXmlApplicationContext類的初始化過程:
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
refresh介紹
refresh方法的具體實作是在AbstractApplicationContext類中如下:
@Override
public void refresh() throws BeansException, IllegalStateException {
//startupShutdownMonitor對象在spring環境重新整理和銷毀的時候都會用到,確定重新整理和銷毀不會同時執行
synchronized (this.startupShutdownMonitor) {
// 準備工作,例如記錄事件,設定标志,檢查環境變量等,并有留給子類擴充的位置,用來将屬性加入到applicationContext中
prepareRefresh();
// 建立beanFactory,這個對象作為applicationContext的成員變量,可以被applicationContext拿來用,
// 并且解析資源(例如xml檔案),取得bean的定義,放在beanFactory中
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 對beanFactory做一些設定,例如類加載器、SPEL解析器、指定bean的某些類型的成員變量對應某些對象.
prepareBeanFactory(beanFactory);
try {
// 子類擴充用,可以設定bean的後置處理器(bean在執行個體化之後這些後置處理器會執行)
postProcessBeanFactory(beanFactory);
// 執行beanFactory後置處理器(有别于bean後置處理器處理bean執行個體,beanFactory後置處理器處理bean定義)
invokeBeanFactoryPostProcessors(beanFactory);
// 将所有的bean的後置處理器排好序,但不會馬上用,bean執行個體化之後會用到
registerBeanPostProcessors(beanFactory);
// 初始化國際化服務
initMessageSource();
// 建立事件廣播器
initApplicationEventMulticaster();
// 空方法,留給子類自己實作的,在執行個體化bean之前做一些ApplicationContext相關的操作
onRefresh();
// 注冊一部分特殊的事件監聽器,剩下的隻是準備好名字,留待bean執行個體化完成後再注冊
registerListeners();
// 單例模式的bean的執行個體化、成員變量注入、初始化等工作都在此完成
finishBeanFactoryInitialization(beanFactory);
// applicationContext重新整理完成後的處理,例如生命周期監聽器的回調,廣播通知等
finishRefresh();
}
catch (BeansException ex) {
logger.warn("Exception encountered during context initialization - cancelling refresh attempt", ex);
// 重新整理失敗後的處理,主要是将一些儲存環境資訊的集合做清理
destroyBeans();
// applicationContext是否已經激活的标志,設定為false
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
}
}
接下來一一介紹下
1.prepareRefresh介紹
protected void prepareRefresh() {
// 設定初始化開始的時間
this.startupDate = System.currentTimeMillis();
// 設定context的關閉狀态為false
this.closed.set(false);
// 設定context的活動狀态是true
this.active.set(true);
if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}
// Initialize any placeholder property sources in the context environment
// 留個子類自己實作的空方法
initPropertySources();
// 驗證對應的key在環境變量中是否存在,如果不存在就抛異常
getEnvironment().validateRequiredProperties();
// earlyApplicationEvents存放早起的一些事件。
this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
}
initPropertySources() 留給子類實作的方法
protected void initPropertySources() {
// For subclasses: do nothing by default.
}
2.obtainFreshBeanFactory()介紹
建立了一個BeanFactory對象
/**
* Tell the subclass to refresh the internal bean factory.
* 子類實作
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 子類(AbstractRefreshableApplicationContext)建立一個ConfigurableListableBeanFactory 對象
refreshBeanFactory();
// 擷取refreshBeanFactory()實作類中建立的BeanFactory對象
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
refreshBeanFactory()
該方法是子類實作的方法,在AbstractRefreshableApplicationContext類中該方法建立了ConfigurableListableBeanFactory 對象并且完成了,并指派給了beanFactory
@Override
protected final void refreshBeanFactory() throws BeansException {
// 如果BeanFactory存在就銷毀
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
// BeanFactory的初始化操作
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
// 在次方法中完成了application.xml檔案的解析
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
// 建立的對象指派給了成員變量beanFactory
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
進入loadBeanDefinitions(beanFactory)方法檢視
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
// 進入該方法檢視
loadBeanDefinitions(beanDefinitionReader);
}
loadBeanDefinitions(beanDefinitionReader);
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
String[] configLocations = getConfigLocations();
if (configLocations != null) {
for (String configLocation : configLocations) {
//繼續進入 configLocation 是applicationContext.xml
reader.loadBeanDefinitions(configLocation);
}
}
}
進入跟蹤
public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
//這是我們在前面文章中初始的ResourceLoader對象
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
}
if (resourceLoader instanceof ResourcePatternResolver) {
// Resource pattern matching available.
try {
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
// 此處進入
int loadCount = loadBeanDefinitions(resources);
if (actualResources != null) {
for (Resource resource : resources) {
actualResources.add(resource);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
}
return loadCount;
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"Could not resolve bean definition resource pattern [" + location + "]", ex);
}
}
else {
// Can only load single resources by absolute URL.
Resource resource = resourceLoader.getResource(location);
int loadCount = loadBeanDefinitions(resource);
if (actualResources != null) {
actualResources.add(resource);
}
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
}
return loadCount;
}
}
繼續跟蹤
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<EncodedResource>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try {
// 擷取applicationContext.xml對應的位元組輸入流
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
// 将配置檔案中的資訊加載到定義的bean中
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
inputStream.close();
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}
跟蹤到如下代碼
try {
Document doc = doLoadDocument(inputSource, resource);
return registerBeanDefinitions(doc, resource);
}
上面是加載bean定義的關鍵代碼:先制作Document對象,再調用registerBeanDefinitions方法,最終會将每個bean的定義放入DefaultListableBeanFactory的beanDefinitionMap中。
getBeanFactory()
擷取refreshBeanFactory()實作類中建立的BeanFactory對象
@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;
}
}
3.prepareBeanFactory
BeanFactory的預準備工作
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 1)、設定BeanFactory的類加載器
beanFactory.setBeanClassLoader(getClassLoader());
// 1)、設定支援表達式解析器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// 2)、添加部分BeanPostProcessor【ApplicationContextAwareProcessor】
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// 3)、設定忽略的自動裝配的接口EnvironmentAware、EmbeddedValueResolverAware、xxx;
// 這些接口的實作類不能通過類型來自動注入
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// 4)、注冊可以解析的自動裝配;我們能直接在任何元件中自動注入:
//BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
/* 其他元件中可以通過下面方式直接注冊使用
@autowired
BeanFactory beanFactory */
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// 5)、添加BeanPostProcessor【ApplicationListenerDetector】後置處理器,在bean初始化前後的一些工作
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// 6)、添加編譯時的AspectJ;
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()));
}
// 7)、給BeanFactory中注冊一些能用的元件;
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
// 環境資訊ConfigurableEnvironment
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
//系統屬性,systemProperties【Map<String, Object>】
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
//系統環境變量systemEnvironment【Map<String, Object>】
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
prepareBeanFactory方法就是為beanFactory做一些設定工作,傳入一些後面會用到的參數和工具類,再在spring容器中建立一些bean;
4.postProcessBeanFactory
postProcessBeanFactory方法是留給子類擴充的,可以在bean執行個體初始化之前注冊後置處理器(類似prepareBeanFactory方法中的beanFactory.addBeanPostProcessor),以子類AbstractRefreshableWebApplicationContext為例,其postProcessBeanFactory方法
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
beanFactory.ignoreDependencyInterface(ServletConfigAware.class);
WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);
}
除了WebApplicationContextUtils類的工作之外,其餘的都是和prepareBeanFactory方法中類似的處理
5.invokeBeanFactoryPostProcessors
nvokeBeanFactoryPostProcessors方法用來執行BeanFactory執行個體的後置處理器BeanFactoryPostProcessor的postProcessBeanFactory方法,這個後置處理器除了原生的,我們也可以自己擴充,用來對Bean的定義做一些修改,由于此時bean還沒有執行個體化,是以不要在自己擴充的BeanFactoryPostProcessor中調用那些會觸發bean執行個體化的方法(例如BeanFactory的getBeanNamesForType方法),源碼的文檔中有相關說明,不要觸發bean的執行個體化,如果要處理bean執行個體請在BeanPostProcessor中進行;
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 (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
6.registerBeanPostProcessors
registerBeanPostProcessors方法的代碼略多,就不在此貼出來了,簡單的說,就是找出所有的bean的後置處理器(注意,是bean的後置處理器,不是beanFactory的後置處理器,bean後置處理器處理的是bean執行個體,beanfactory後置處理器處理的是bean的定義),然後将這些bean的後置處理器分為三類:
實作了順序接口Ordered.class的,先放入orderedPostProcessors集合,排序後順序加入beanFactory的bean後處理集合中;
既沒有實作Ordered.class,也沒有實作PriorityOrdered.class的後置處理器,也加入到beanFactory的bean後處理集合中;
最後是實作了優先級接口PriorityOrdered.class的,排序後順序加入beanFactory的bean後處理集合中;
registerBeanPostProcessors方法執行完畢後,beanFactory中已經儲存了有序的bean後置處理器,在bean執行個體化之後,會依次使用這些後置處理器對bean執行個體來做對應的處理;
7.initMessageSource
initMessageSource方法用來準備國際化資源相關的,将實作了MessageSource接口的bean存放在ApplicationContext的成員變量中,先看是否有配置,如果有就執行個體化,否則就建立一個DelegatingMessageSource執行個體的bean
8.initApplicationEventMulticaster
spring中有事件、事件廣播器、事件監聽器等組成事件體系,在initApplicationEventMulticaster方法中對事件廣播器做初始化,如果找不到此bean的配置,就建立一個SimpleApplicationEventMulticaster執行個體作為事件廣播器的bean,并且儲存為applicationContext的成員變量applicationEventMulticaster
/**
* Initialize the ApplicationEventMulticaster.
* Uses SimpleApplicationEventMulticaster if none defined in the context.
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
protected void initApplicationEventMulticaster() {
//擷取BeanFactory
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 判斷是否存在
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
// 從容器中擷取ApplicationEventMulticaster對象
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isDebugEnabled()) {
logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
// 初始一個SimpleApplicationEventMulticaster對象
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
// 建立的對象注冊到BeanFactory中
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
"': using default [" + this.applicationEventMulticaster + "]");
}
}
}
9.onRefresh
onRefresh是個空方法,留給子類自己實作的,在執行個體化bean之前做一些ApplicationContext相關的操作,以子類AbstractRefreshableWebApplicationContext為例,看看它的onRefresh方法
/**
* Initialize the theme capability.
*/
@Override
protected void onRefresh() {
this.themeSource = UiApplicationContextUtils.initThemeSource(this);
}
10.registerListeners
方法名為registerListeners,看名字像是将監聽器注冊在事件廣播器中,但實際情況并非如此,隻有一些特殊的監聽器被注冊了,那些在bean配置檔案中實作了ApplicationListener接口的類還沒有執行個體化,是以此處隻是将其name儲存在廣播器中,将這些監聽器注冊在廣播器的操作是在bean的後置處理器中完成的,那時候bean已經執行個體化完成了,我們看代碼
protected void registerListeners() {
// 注冊的都是特殊的事件監聽器,而并非配置中的bean
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);
}
}
11.finishBeanFactoryInitialization
finishBeanFactoryInitialization方法做了兩件事:
beanFactory對象的初始化;
我們在bean配置檔案中配置的那些單例的bean,都是在finishBeanFactoryInitialization方法中執行個體化的;
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
// 執行個體化類型轉換的bean,并儲存在ApplicationContext中
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
// 執行個體化LoadTimeWeaverAware接口的bean,用于ApsectJ的類加載期織入的處理
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
// 確定臨時的classLoader為空,臨時classLoader一般被用來做類型比對的
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
// 将一個标志設定為true,表示applicationContext已經緩存了所有bean的定義,這些bean的name都被儲存在applicationContext的frozenBeanDefinitionNames成員變量中,相當于一個快照,記錄了目前那些bean的定義已經拿到了
beanFactory.freezeConfiguration();
// 執行個體化所有還未執行個體化的單例bean
beanFactory.preInstantiateSingletons();
}
preInstantiateSingletons方法
public void preInstantiateSingletons() throws BeansException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("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<String>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
// 擷取bean的定義,該定義已經和父類定義做了合并
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 非抽象類、是單例、非懶加載
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//FactoryBean的處理
if (isFactoryBean(beanName)) {
final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return ((SmartFactoryBean<?>) factory).isEagerInit();
}
}, getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
else {
//非FactoryBean的執行個體化、初始化
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
// 單例執行個體化完成後,如果實作了SmartInitializingSingleton接口,afterSingletonsInstantiated就會被調用,此處用到了特權控制邏輯AccessController.doPrivileged
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
smartSingleton.afterSingletonsInstantiated();
return null;
}
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
doGetBean
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
/**
2、先擷取緩存中儲存的單執行個體Bean。如果能擷取到說明這個Bean之前被建立過(所有建立過的單執行個體Bean都會被緩存起來)
從private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);擷取的
**/
Object sharedInstance = getSingleton(beanName);
//如果沒有擷取到建立bean
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {//3、緩存中擷取不到,開始Bean的建立對象流程;
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// 擷取父beanFatory 檢查這個bean是否建立了
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (args != null) {
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
// 4、标記目前bean已經被建立
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
// 5、擷取Bean的定義資訊;
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// 6、【擷取目前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);
getBean(dep); //先建立依賴的bean
}
}
// 啟動單執行個體的bean的建立流程
if (mbd.isSingleton()) {
//擷取到單執行個體bean後,添加到緩存中 singletonObjects()
//Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
//建立Bean
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
// 下面部分不重要了
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
doCreateBean方法
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
// bean的包裝
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 1)、【建立Bean執行個體】利用工廠方法或者對象的構造器建立出Bean執行個體;
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
mbd.resolvedTargetType = beanType;
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//調用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition(mbd, beanType, beanName);
//判斷是否為:MergedBeanDefinitionPostProcessor 類型的,如果是,調用方法
//MergedBeanDefinitionPostProcessor 後置處理器是在bean執行個體換之後調用的
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
//判斷bean 是否為單執行個體的,如果是單執行個體的添加到緩存中
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
//添加bean到緩存中
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
//為bean 指派
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
// 4)、【Bean初始化】
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
if (earlySingletonExposure) {
//擷取單執行個體bean,此時已經建立好了
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// 5)、注冊實作了DisposableBean 接口Bean的銷毀方法;隻是注冊沒有去執行,容器關閉之後才去調用的
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
populateBean()建立bean後屬性指派
//populateBean():1204, AbstractAutowireCapableBeanFactory
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
PropertyValues pvs = mbd.getPropertyValues();
if (bw == null) {
if (!pvs.isEmpty()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
return;
}
}
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
boolean continueWithPropertyPopulation = true;
//指派之前:
/* 1)、拿到InstantiationAwareBeanPostProcessor後置處理器;
執行處理器的postProcessAfterInstantiation(); 方法*/
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//執行
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// autowire 按name注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// autowire 按類型注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
/*2)、拿到InstantiationAwareBeanPostProcessor後置處理器;
執行 postProcessPropertyValues(); 擷取到屬性的值,此時還未指派*/
if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
//=====指派之前:===
//3)、應用Bean屬性的值;為屬性利用setter方法等進行指派;
applyPropertyValues(beanName, mbd, bw, pvs);
}
Bean初始化 initializeBean
//初始化
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
//1)、【執行Aware接口方法】invokeAwareMethods(beanName, bean);執行xxxAware接口的方法
//判斷是否實作了 BeanNameAware\BeanClassLoaderAware\BeanFactoryAware 這些接口的bean,如果是執行相應的方法
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//2)、【執行後置處理器BeanPostProcessor初始化之前】 執行所有的 BeanPostProcessor.postProcessBeforeInitialization();
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//3)、【執行初始化方法】
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
//4)、【執行後置處理器初始化之後】 執行所有的beanProcessor.postProcessAfterInitialization(result, beanName);方法
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
38
執行bean的初始化方法init
1)是否是InitializingBean接口的實作;執行接口規定的初始化;
2)是否自定義初始化方法;通過注解的方式添加了initMethod方法的,
例如: @Bean(initMethod=“init”,destroyMethod=“detory”)
//invokeInitMethods():1667, AbstractAutowireCapableBeanFactory
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
//1)、是否是InitializingBean接口的實作;執行接口規定的初始化 ,執行afterPropertiesSet()這個方法;
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
((InitializingBean) bean).afterPropertiesSet();
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
//執行實作InitializingBean的afterPropertiesSet方法
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null) {
//執行通過注解自定義的initMethod 方法
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
12.finishRefresh
最後一個方法是finishRefresh,這是在bean的執行個體化、初始化等完成後的一些操作,例如生命周期變更的回調,發送applicationContext重新整理完成的廣播等,展開看看
protected void finishRefresh() {
// 檢查是否已經配置了生命周期處理器,如果沒有就new一個DefaultLifecycleProcessor
initLifecycleProcessor();
// 找到所有實作了Lifecycle接口的bean,按照每個bean設定的生命周期階段進行分組,再依次調用每個分組中每個bean的start方法,完成生命周期監聽的通知
getLifecycleProcessor().onRefresh();
// 建立一條代表applicationContext重新整理完成的事件,交給廣播器去廣播
publishEvent(new ContextRefreshedEvent(this));
// 如果配置了MBeanServer,就完成在MBeanServer上的注冊
LiveBeansView.registerApplicationContext(this);
}
Spring啟動流程總結
Spring容器在啟動的時候,先會儲存所有注冊進來的Bean的定義資訊;
1.1 xml注冊bean;
1.2 注解注冊Bean;@Service、@Component、@Bean、xxx
Spring容器會合适的時機建立這些Bean
2.1用到這個bean的時候;利用getBean建立bean;建立好以後儲存在容器中;
2.2統一建立剩下所有的bean的時候;finishBeanFactoryInitialization();
後置處理器;BeanPostProcessor
每一個bean建立完成,都會使用各種後置處理器進行處理;來增強bean的功能;
AutowiredAnnotationBeanPostProcessor:處理自動注入
AnnotationAwareAspectJAutoProxyCreator:來做AOP功能;
事件驅動模型;
ApplicationListener;事件監聽;
ApplicationEventMulticaster;事件派發: