一、首先上一个关于ClassPathXmlApplicationContext类关系图,其中的操作都是核心方法:
二、1.ClassPathXmlApplicationContext加载xml配置文件原理:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(*.xml, getClass());
assertTrue(ctx.containsBean("beanName"));
ctx.getBean("beanName");
上面执行过程如下:
(1)首先调用构造函数ClassPathXmlApplicationContext(String path, Class<?> clazz)一直调用到ClassPathXmlApplicationContext(String[] paths, Class<?> clazz, ApplicationContext parent)此构造函数中的refresh()方法,此方法相当重要,调用到父类AbstractApplicationContext的refresh方法,用到模板模式,核心是加载xml配置文件,在load之前和之后可以重写其中的很多方法加入自己的操作逻辑,例如:postProcessBeanFactory方法就是留给子类重写的,然后去调用类AbstractRefreshableApplicationContext的refreshBeanFactory方法去loadBeanDefinitions(在类AbstractXmlApplicationContext中),核心代码如下:
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(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually load