What is the order and principle of spring loading?
Spring loads in order from top to bottom and from inner to outer.
The specific loading process is as follows:
- Load configuration file: Spring will load and parse the content based on the specified path in the configuration file.
- Creating Bean definitions: Spring will generate corresponding Bean definition objects based on the definitions in the configuration file, and store them in the Bean definition container.
- Scan Bean components: Spring scans the specified package path, searches for classes with specific annotations, and converts them into Bean components.
- Bean registration: Spring will convert the scanned Bean components into corresponding Bean definitions and register them in the Bean definition container.
- Instantiating a Bean: Spring will instantiate the corresponding Bean object based on the information in the Bean definition within the container.
- Property Injection: Spring will inject the required properties into the corresponding Bean object based on the information in the Bean definition container.
- Spring will call the initialization method of the Bean object to carry out necessary initialization operations.
- Register Bean object: Spring will save the initialized Bean object into the Bean container.
- Loading completed: The loading process ends once Spring has completed all initialization operations.
The principle of Spring loading is primarily achieved through the implementation of two core interfaces, BeanFactory and ApplicationContext.
- BeanFactory is the most foundational container in Spring, responsible for managing and controlling the lifecycle of beans, which includes operations such as instantiation, initialization, and destruction.
- The ApplicationContext is an extension of the BeanFactory, offering additional features such as internationalization support and event publishing. During the loading process, the ApplicationContext first creates the BeanFactory and then uses different loading strategies, such as loading XML files or performing annotation scanning, based on the configuration file.
The loading process of Spring is lazy loading, which means the Bean will only be loaded and initialized when needed, so as to improve performance and resource utilization efficiency. Additionally, Spring also provides some extension points, such as BeanPostProcessor and BeanFactoryPostProcessor, which allow for custom operations and processing of Beans during the loading process.