Refresh Spring container ()
PrepareRefresh () pretreatment before the refresh;
1) initPropertySources() initializes some property Settings; Subclass user-defined personalized attribute setting method; 2), getEnvironment (.) validateRequiredProperties (); EarlyApplicationEvents = new LinkedHashSet<ApplicationEvent>(); Save some of the earlier events in the container;Copy the code
2, obtainFreshBeanFactory (); To obtain the BeanFactory;
1), refreshBeanFactory (); Refresh [create] BeanFactory; Create a enclosing the beanFactory = new DefaultListableBeanFactory (); Set the id; 2), getBeanFactory (); Return just GenericApplicationContext created the BeanFactory object; 3), will create the BeanFactory DefaultListableBeanFactory 】 【 return;Copy the code
3, prepareBeanFactory (the beanFactory); BeanFactory preparation (BeanFactory does some setup);
1) Set BeanFactory class loader, support expression parser... 2), add some BeanPostProcessor ApplicationContextAwareProcessor 】 【 3), set to ignore automatic assembly interface EnvironmentAware, EmbeddedValueResolverAware, XXX; 4) Register resolvable auto assembly; We can automatically inject directly into any component: The BeanFactory, ResourceLoader, ApplicationEventPublisher, ApplicationContext 5), add BeanPostProcessor ApplicationListenerDetector 】 【 6), add a compile-time AspectJ; 7) Register some useful components in BeanFactory; ConfigurableEnvironment [Map<String, Object>], systemProperties [Map<String, Object>]Copy the code
4, postProcessBeanFactory (the beanFactory);
Post-processing after BeanFactory preparation work is completed;
1) Subclasses override this method to set up the BeanFactory after it has been created and prepreparedCopy the code
The above is the creation and preparation of BeanFactory
5, invokeBeanFactoryPostProcessors (the beanFactory);
Implement BeanFactoryPostProcessor methods; BeanFactoryPostProcessor: the backend processor of BeanFactory. Executed after the BeanFactory standard is initialized; Two interfaces: spring BeanFactoryPostProcessor, BeanDefinitionRegistryPostProcessor
1) Implement BeanFactoryPostProcessor method; Perform BeanDefinitionRegistryPostProcessor 1) first, obtain all BeanDefinitionRegistryPostProcessor; 2), the first implementation implements PriorityOrdered interface BeanDefinitionRegistryPostProcessor priority, PostProcessor. PostProcessBeanDefinitionRegistry (registry) 3), realized the Ordered sequence interface in the implementation of the BeanDefinitionRegistryPostProcessor; PostProcessor. PostProcessBeanDefinitionRegistry (registry) 4), the final execution does not implement any priority or BeanDefinitionRegistryPostProcessors sequence interface; PostProcessor. PostProcessBeanDefinitionRegistry (registry) to perform the spring BeanFactoryPostProcessor method 1) Obtain all BeanFactoryPostProcessors 2) execute BeanFactoryPostProcessor which implements PriorityOrdered priority PostProcessor. PostProcessBeanFactory () 3), realized the Ordered sequence interface in the implementation of the spring BeanFactoryPostProcessor; PostProcessor. PostProcessBeanFactory (4), the final execution don't implement any priority or spring BeanFactoryPostProcessor sequence interface; postProcessor.postProcessBeanFactory()Copy the code
6, registerBeanPostProcessors (the beanFactory);
Register BeanPostProcessor for different interface types Execution timing is different before and after Bean creation
BeanPostProcessor, DestructionAwareBeanPostProcessor, InstantiationAwareBeanPostProcessor, SmartInstantiationAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor [internalPostProcessors], 1) and for all BeanPostProcessor; Postulated processors can run the PriorityOrdered, Ordered interface by default, registering the BeanPostProcessor of the PriorityOrdered priority interface. Put every BeanPostProcessor; Added to the BeanFactory the BeanFactory. AddBeanPostProcessor (postProcessor); 3), registered again Ordered the 4) of the interface, the final register don't implement any interface priority of 5), the final register MergedBeanDefinitionPostProcessor; 6), registered a ApplicationListenerDetector; Whether to create after the completion of the inspection on the Bean is ApplicationListener, if is the applicationContext. AddApplicationListener ((ApplicationListener <? >) bean);Copy the code
7, initMessageSource (); Initialize the MessageSource component (do internationalization; Message binding, message parsing);
[BeanFactory] [BeanFactory] [DelegatingMessageSource] [DelegatingMessageSource] [DelegatingMessageSource] MessageSource: Retrieves the value of a key in the internationalization configuration file Can be obtained according to regional information; 3) Register the MessageSource in the container. When the value of the internationalization profile is obtained, the MessageSource can be injected automatically. beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); MessageSource.getMessage(String code, Object[] args, String defaultMessage, Locale locale);Copy the code
8, initApplicationEventMulticaster (); Initialize the event dispatcher;
1), 2) to obtain the BeanFactory, obtaining from the BeanFactory applicationEventMulticaster applicationEventMulticaster; 3) If the previous step is not configured; Create a SimpleApplicationEventMulticaster 4), will create ApplicationEventMulticaster added to the BeanFactory, other components automatically injected directly in the futureCopy the code
9, onRefresh (); Leave it to child containers (subclasses)
Subclasses override this method to customize the logic when the container is refreshed.Copy the code
10, registerListeners (); Register ApplicationListener for all projects in the container.
Get all applicationListeners from the container. Add each listener to the event dispatcher. getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); 3. Distribute events generated in previous steps;Copy the code
11, finishBeanFactoryInitialization (the beanFactory); Initialize all remaining single-instance beans;
1, the beanFactory. PreInstantiateSingletons (); 1) Get all beans in the container, initialize and create objects in turn 2) get bean definition information; RootBeanDefinition 3), Bean is not abstract, is a single instance, not lazy loading; 1) Determine if it is a FactoryBean; Is a Bean that implements the FactoryBean interface; 2) Not factory beans. Using getBean (beanName); Create object 0, getBean(beanName); ioc.getBean(); DoGetBean (name, null, null, false); 2. Get the single-instance Bean stored in the cache. If available, the Bean was previously created (all created singleton beans are cached) from the private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256); 3. The object creation process of the Bean is started because it cannot be obtained in the cache. 5. Get the bean definition information. GetBean (); getBean(); getBean(); getBean(); 7. Start the creation process of the single-instance Bean; CreateBean (beanName, MBD, args); (2), Object bean = resolveBeforeInstantiation beanName, mbdToUse); Let BeanPostProcessor intercept the return proxy object first; 【 InstantiationAwareBeanPostProcessor 】 : early implementation; Trigger: first postProcessBeforeInstantiation (); If there is a return value: the trigger postProcessAfterInitialization (); 3), if the previous InstantiationAwareBeanPostProcessor does not return a proxy object; Object beanInstance = doCreateBean(beanName, mbdToUse, args); 1), [create Bean instance]; createBeanInstance(beanName, mbd, args); Create Bean instances using factory methods or object constructors; 2), applyMergedBeanDefinitionPostProcessors (MBD, beanType, beanName); Call MergedBeanDefinitionPostProcessor postProcessMergedBeanDefinition (MBD, beanType, beanName); PopulateBean (beanName, MBD, instanceWrapper); Before the assignment: 1), to the rear InstantiationAwareBeanPostProcessor processor; PostProcessAfterInstantiation (); 2), to the rear InstantiationAwareBeanPostProcessor processor; PostProcessPropertyValues (); ===== before assigning: === 3), apply the Bean property value; Assign values to attributes using setter methods, etc. applyPropertyValues(beanName, mbd, bw, pvs); InitializeBean (beanName, exposedObject, MBD); 1). [invokeAwareMethods(beanName, bean)] The method to implement the xxxAware interface BeanNameAware\BeanClassLoaderAware\BeanFactoryAware 2), 【 】 post processor initialized before applyBeanPostProcessorsBeforeInitialization (wrappedBean, beanName); BeanPostProcessor. PostProcessBeforeInitialization (); 3) invokeInitMethods(beanName, wrappedBean, MBD); 1) Whether it is the implementation of InitializingBean interface; Perform initialization as specified by the interface; 2) Whether to customize the initialization method; 4), executive post processor initialized 】 【 applyBeanPostProcessorsAfterInitialization BeanPostProcessor. PostProcessAfterInitialization (); 5) Destruction method of registered Bean; 5) Add the created Bean to the cache singletonObjects; The IOC container is these maps; Many maps contain single-instance beans, environment information... ; All beans are created using getBean; Check whether all the Bean SmartInitializingSingleton interface; If it is; Is executed afterSingletonsInstantiated ();Copy the code
12, finishRefresh (); Complete the initialization of BeanFactory; The IOC container is created;
1), initLifecycleProcessor (); Initialize the post-processor associated with the life cycle; By default, LifecycleProcessor checks whether there are LifecycleProcessor components in the container. If there is no new DefaultLifecycleProcessor (); Add to container; Write a LifecycleProcessor implementation class in BeanFactory void onRefresh(); void onClose(); 2), getLifecycleProcessor (.) onRefresh (); Get the life cycle handler (BeanFactory) defined above; The callback onRefresh (); PublishEvent (new ContextRefreshedEvent(this)); Publish container refresh completion events 4), liveBeansView. RegisterApplicationContext (this);Copy the code
conclusion
1) When the Spring container is started, it will first save the definition information of all registered beans; 1) XML registered bean; <bean> 2). @service, @Component, @bean, XXX 2), the Spring container will create these beans when appropriate 1), when the Bean is used; Create a bean using getBean; Once created, it is stored in a container. 2) When all the remaining beans are created; FinishBeanFactoryInitialization (); 3) Rear processor; BeanPostProcessor 1) After each bean is created, various post-processors will be used for processing; To enhance bean functionality; AutowiredAnnotationBeanPostProcessor: processing automatic injection AnnotationAwareAspectJAutoProxyCreator: to make AOP functionality; xxx.... Enhance the function of the annotation: AsyncAnnotationBeanPostProcessor... 4) Event-driven model; ApplicationListener; Event listening; ApplicationEventMulticaster; Event Distribution:Copy the code