spring通过加载配置文件的方式来装载初始化bean。以下面的使用为例:
ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:performer.xml");
Performer performer = (Performer) ctx.getBean("duke");
performer.perform();
主要使用到FileSystemXmlApplicationContext,该类的继承结构如下:
AbrstactApplicationContext类做为基本抽象类,实现了大部分方法并且提供了程序基本的运行框架。
在运行过程中,该类的refresh方法会调用obtainFreshBeanFactory方法。通过一步步程序运行定位到
子类AbstractRefreshableApplicationContext中的refreshBeanFactory()方法。
protected final void refreshBeanFactory() throws BeansException {
...
DefaultListableBeanFactory beanFactory = createBeanFactory();//初始化beanFactory
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);//装载 bean的定义文件
...
其中loadBeanDefinitions具体是由子类AbstractXmlApplicationContext实现
1 protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
2 // Create a new XmlBeanDefinitionReader for the given BeanFactory.
3 XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
4 beanDefinitionReader.setEnvironment(this.getEnvironment());
5 beanDefinitionReader.setResourceLoader(this);
6 beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
7 initBeanDefinitionReader(beanDefinitionReader);
8 loadBeanDefinitions(beanDefinitionReader);
}
跟踪代码到 类XmlBeanDefinitionReader中 (此时已经获取到配置文件的inputStream流)
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {