This section talks about Spring bean initialization (3) - ApplicationContext
Both ApplicationContext and BeanFactory are used to load beans, but ApplicationContext is basically used in the project because it includes all the functions of BeanFactory and has been extended. During the initialization process of ApplicationContext, all singletons (no-lazy- init) initialization
ApplicationContext ctx = new ClassPathXmlApplicationContext("/spring-code-test.xml"); SysArgDAO bean = (SysArgDAO) ctx.getBean("sysArgDAO");
Let's take a look at the specific code implementation of ClassPathXmlApplicationContext
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException { super(parent); // Support array method to pass in xml configuration file setConfigLocations(configLocations); if (refresh) { // core logic refresh(); } }
refresh includes the core logic, in the class AbstractApplicationContext
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // This step will complete the xml loading, and put the properties into the beanFactory, completing the "Spring bean initialization (1)" ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Execute BeanFactoryPostProcessor, which is the function of applicationcontext extension to ensure customization before bean initialization // For example, PropertyPlaceholderConfigurer will handle variable parsing and substitution in xml (such as <value>${jdbc.url}</value> ) to ensure completion before bean initialization invokeBeanFactoryPostProcessors(beanFactory); // Register the BeanPostProcessor method, you can directly register the BeanPostProcessor implementation in the configuration file, the method will be called in the process of getBean, and execute the method customized by applicationcontext to process the bean registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); // instantiate all non-lazy-init singletons finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); }