接上文Spring 学习记录7 初识XmlWebApplicationContext

 

refresh方法

refresh方法是定义在父类AbstractApplicationContext中的.它内部会调用很多方法.有一些是在子类中实现的.算是模板方法的设计模式吧.主要作用就是初始化wac加载各种bean等作用.

 1 @Override
 2     public void refresh() throws BeansException, IllegalStateException {
 3         synchronized (this.startupShutdownMonitor) {
 4             // Prepare this context for refreshing.
 5             // 记录开始wac开始初始化的时间,设置激活标记,servlet的相关param设置到env(之前做过1次),校验env中必须的props
 6             prepareRefresh();
 7 
 8             // Tell the subclass to refresh the internal bean factory.
 9             // 刷新初始化BF并获取它,将旧的BF里的bean删掉,新建1个BF,加载XML配置文件
10             ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
11 
12             // Prepare the bean factory for use in this context.
13             prepareBeanFactory(beanFactory);
14 
15             try {
16                 // Allows post-processing of the bean factory in context subclasses.
17                 postProcessBeanFactory(beanFactory);
18 
19                 // Invoke factory processors registered as beans in the context.
20                 invokeBeanFactoryPostProcessors(beanFactory);
21 
22                 // Register bean processors that intercept bean creation.
23                 registerBeanPostProcessors(beanFactory);
24 
25                 // Initialize message source for this context.
26                 initMessageSource();
27 
28                 // Initialize event multicaster for this context.
29                 initApplicationEventMulticaster();
30 
31                 // Initialize other special beans in specific context subclasses.
32                 onRefresh();
33 
34                 // Check for listener beans and register them.
35                 registerListeners();
36 
37                 // Instantiate all remaining (non-lazy-init) singletons.
38                 finishBeanFactoryInitialization(beanFactory);
39 
40                 // Last step: publish corresponding event.
41                 finishRefresh();
42             } catch (BeansException ex) {
43                 logger.warn("Exception encountered during context initialization - cancelling refresh attempt", ex);
44 
45                 // Destroy already created singletons to avoid dangling resources.
46                 destroyBeans();
47 
48                 // Reset 'active' flag.
49                 cancelRefresh(ex);
50 
51                 // Propagate exception to caller.
52                 throw ex;
53             }
54         }
55     }
View Code

相关文章: