Let’s look a simple code within Spring below:
1 | // create and configure beans |
First of all, we should know the class hierarchy in org.springframework.context.support:
ClassPathXmlApplicationContext implements ApplicationContext and calls its constructor as below:
1 | /** |
Step into ClassPathXmlApplicationContext(String[], boolean, ApplicationContext):
1 | /** |
In this method, it first call super(parent), which is AbstractXmlApplicationContext(parent) –> AbstractRefreshableConfigApplicationContext(parent) –> AbstractRefreshableApplicationContext(parent) –> AbstractApplicationContext(parent).
Then, for the setConfigLocations(configLocations), we need move to AbstractRefreshableConfigApplicationContext, the superclass of ClassPathXmlApplicationContext. It has setConfigLocations(configLocations) that deals with the locations String and save to its private value String[] configLocations.
Now, we get to the refresh() method belong to AbstractApplicationContext that implements the method in the interface ConfigurableApplicationContext
1 | /** |
For this line call obtainFreshBeanFactory() that then calls refreshBeanFactory(), subclass AbstractXmlApplicationContext to refresh bean factory and load bean definitions by calling loadBeanDefinitions(beanFactory), and then it calls loadBeanDefinitions(reader), in which reader is XmlBeanDefinitionReader implements BeanDefinitionReader. This class loads a DOM document and applies the reader to it. The document reader will register each bean definition with the given bean factory, talking to the latter’s implementation of the BeanDefinitionRegistry interface.
1 | // Tell the subclass to refresh the internal bean factory. |
The reader has the loadBeanDefinitions(configLocations) method and the inner method of XmlBeanDefinitionReader provides a loadBeanDefinitions(encodedResource) where EncodedResource is the resource descriptor for the XML file, allowing to specify an encoding to use for parsing the file.
Method doLoadDocument(inputSource, resource) actually load bean definitions from the specified XML file. DefaultDocumentLoader that implements DocumentLoader loads a Document document from the supplied InputSource source by calling method loadDocument(InputSource, EntityResolver, ...) (that is a classical design pattern).
Further topics: InputSource of Spring Resource,ThreadLocal of Java SE concurrency, context.getBean(...) of how to get instantialization of service.