In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the Spring IOC initialization execution process". In the daily operation, I believe that many people have doubts about what the Spring IOC initialization execution process is. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what is the Spring IOC initialization execution process?" Next, please follow the editor to study!
Operating environment: jdk8,springboot-2.2.2
The initialization core of Spring IOC container lies in the refresh method of AbstractApplicationContext.
General process of refresh method execution
Get the BeanFactory and do some preparations for BeanFactory
Post processor that executes BeanFactory
Create and register other post processors
Initialize MessageSource components (internationalization function; message binding, message parsing)
Initialize event dispatcher, register listener
Create the remaining non-lazily loaded single instance bean
Put the finishing touches to work. Create the release container, clean up some caches, etc.
The actual type of ApplicationContext that executes the refresh () method under SpringBoot is AnnotationConfigServletWebServerApplicationContext
For the structure of AnnotationConfigServletWebServerApplicationContext, please see here.
PrepareRefresh ()
Activate the container
This.startupDate = System.currentTimeMillis (); this.closed.set (false); this.active.set (true)
Create early event listeners and early events
This.earlyApplicationListeners = new LinkedHashSet (this.applicationListeners); this.earlyApplicationEvents = new LinkedHashSet (); ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory ()
Set a serialization ID for the member variable private final DefaultListableBeanFactory beanFactory of the subclass GenericApplicationContext class
RefreshBeanFactory (); this.beanFactory.setSerializationId (getId ())
Returns the member variable private final DefaultListableBeanFactory beanFactory of the subclass GenericApplicationContext class
Return type is ConfigurableListableBeanFactory
Return getBeanFactory ()
The beanFactory of GenericApplicationContext is new when the context object is created.
PrepareBeanFactory (beanFactory)
Some preparatory work has been done for beanFactory
Set up the class loader used by beanFactory, and set up a parser for parsing expressions (such as parsing ${} or # {} expressions)
BeanFactory.setBeanClassLoader (getClassLoader ()); beanFactory.setBeanExpressionResolver (new StandardBeanExpressionResolver (beanFactory.getBeanClassLoader ()
Some post processors have been added
BeanFactory.addBeanPostProcessor (new ApplicationContextAwareProcessor (this)); beanFactory.addBeanPostProcessor (new ApplicationListenerDetector (this))
Some interfaces that cannot be automatically assembled are set up.
BeanFactory.ignoreDependencyInterface (EnvironmentAware.class);... beanFactory.ignoreDependencyInterface (ApplicationContextAware.class)
Registered some interfaces that can be automatically assembled.
BeanFactory.registerResolvableDependency (BeanFactory.class, beanFactory);... beanFactory.registerResolvableDependency (ApplicationContext.class, this)
Add:
ApplicationListenerDetector's postProcessAfterInitialization (Object bean, String beanName) executes after bean is created with an instantiated object
Function: if this bean is ApplicationListener, execute this.applicationContext.addApplicationListener ((ApplicationListener) bean)
BeanFactory.ignoreDependencyInterface specifies interfaces that are ignored in automatic assembly
BeanFactory.registerResolvableDependency (Class dependencyType, @ Nullable Object autowiredValue) specifies the default object for automatic assembly.
It works a bit like @ Primary annotations.
PostProcessBeanFactory (beanFactory)
This method is empty and is left to the subclass for implementation.
InvokeBeanFactoryPostProcessors (beanFactory)
Execute two post processors
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors (beanFactory, getBeanFactoryPostProcessors ())
Execution sequence
PostProcessBeanDefinitionRegistry of BeanDefinitionRegistryPostProcessor
PostProcessBeanFactory of BeanDefinitionRegistryPostProcessor
PostProcessBeanFactory of BeanFactoryPostProcessor
It contains the process for creating a BeanDefinition:
ConfigurationClassPostProcessor's postProcessBeanDefinitionRegistry method creates a BeanDefinition for all components in the package and subpackage where the startup class resides and adds it to the DefaultListableBeanFactory member variable this.BeanDefinitionMap.
Here is the method stack to scan and get the component
/ you can see all the components of BeanDefinition to be created doScan:292, ClassPathBeanDefinitionScanner (org.springframework.context.annotation) parse:132, ComponentScanAnnotationParser (org.springframework.context.annotation) doProcessConfigurationClass:290, ConfigurationClassParser (org.springframework.context.annotation) processConfigurationClass:245, ConfigurationClassParser (org.springframework.context.annotation) parse:202, ConfigurationClassParser (org.springframework.context.annotation) parse:170, ConfigurationClassParser (org.springframework.context.annotation) processConfigBeanDefinitions:325 under your basePackages (the package where the main startup class is located) in the org.springframework.context.annotation method. ConfigurationClassPostProcessor (org.springframework.context.annotation) postProcessBeanDefinitionRegistry:242, ConfigurationClassPostProcessor (org.springframework.context.annotation) invokeBeanDefinitionRegistryPostProcessors:275, PostProcessorRegistrationDelegate (org.springframework.context.support) invokeBeanFactoryPostProcessors:95, PostProcessorRegistrationDelegate (org.springframework.context.support) invokeBeanFactoryPostProcessors:706, AbstractApplicationContext (org.springframework.context.support) refresh:532, AbstractApplicationContext (org.springframework.context.support)
On the difference between postProcessBeanDefinitionRegistry of BeanDefinitionRegistryPostProcessor and postProcessBeanFactory of BeanFactoryPostProcessor
The timing of execution is different. The comments on these two methods say
The postProcessBeanDefinitionRegistry method is called when the bean definition information (BeanDefinition object) is not loaded and no bean is instantiated after the container standard initialization is complete. At this point, you can also add new or overwrite old bean definition information to the container
The postProcessBeanFactory method is called when all the bean definition information has been loaded after the container standard initialization is complete, but the temperature and bean have not yet been instantiated. The execution time is later than the postProcessBeanDefinitionRegistry method.
RegisterBeanPostProcessors (beanFactory)
Add a post processor to the container
PostProcessorRegistrationDelegate.registerBeanPostProcessors (beanFactory, this)
Add a post processor to the container
BeanFactory.addBeanPostProcessor (new BeanPostProcessorChecker (beanFactory, beanProcessorTargetCount))
There are four categories to register custom post processors
/ / implement PriorityOrdered interface List priorityOrderedPostProcessors = new ArrayList (); / / implement PriorityOrdered interface with MergedBeanDefinitionPostProcessor type List internalPostProcessors = new ArrayList (); / / implement List orderedPostProcessorNames = new ArrayList () of Ordered interface; / / List nonOrderedPostProcessorNames = new ArrayList () that does not implement PriorityOrdered or Ordered interface
First add the post processor to different List according to the above rules, and then sort it.
Then create the instance object of the post processor
Then add the instance object to the container (the member variable private final List beanPostProcessors of AbstractBeanFactory = new CopyOnWriteArrayList ();)
Add a post processor to the container
BeanFactory.addBeanPostProcessor (new ApplicationListenerDetector (applicationContext))
Add:
The MergedBeanDefinitionPostProcessor interface is used to do dependency injection when creating a bean
InitMessageSource ()
Initialize MessageSource components (internationalization function; message binding, message parsing)
Check to see if there is a bean with beanName = "messageSource" in the container. If there is no new, assign it to this.messageSource, and then add it to the container
You can inject this bean later and execute its getMessage method to get the contents of the internationalization configuration file
InitApplicationEventMulticaster ()
Initialize event dispatcher
Check to see if there is a bean with beanName = "applicationEventMulticaster" in the container. If there is no new, assign it to this.applicationEventMulticaster, and then add it to the container
OnRefresh ()
This method is empty and is left to the subclass for implementation.
RegisterListeners ()
Add the AbstractApplicationContext member variable this.applicationListeners event listener to the event dispatcher
For (ApplicationListener listener: getApplicationListeners ()) {getApplicationEventMulticaster () .addApplicationListener (listener);}
Add the name of the event listener in the container to the event dispatcher
String [] listenerBeanNames = getBeanNamesForType (ApplicationListener.class, true, false); for (String listenerBeanName: listenerBeanNames) {getApplicationEventMulticaster () .addApplicationListenerBean (listenerBeanName);}
Publish early this.earlyApplicationEvents events and clean up early events
Set earlyEventsToProcess = this.earlyApplicationEvents;this.earlyApplicationEvents = null;if (earlyEventsToProcess! = null) {for (ApplicationEvent earlyEvent: earlyEventsToProcess) {getApplicationEventMulticaster () .multicastEvent (earlyEvent);}}
FinishBeanFactoryInitialization (beanFactory)
= = create the remaining single instance bean== that is not lazily loaded
/ / create the remaining non-lazy loading single instance beanfinishBeanFactoryInitialization (beanFactory); / / call beanFactory to create the remaining non-lazy loading single instance bean beanFactory.preInstantiateSingletons (); / / get and traverse the beanNames, and use beanName to get BeanDefinition RootBeanDefinition bd = getMergedLocalBeanDefinition (beanName); getBean (beanName) DoGetBean (name, null, null, false); / / try to get the bean from the container, and create your own bean if you can't get it. The getSingleton method is the method Object sharedInstance= getSingleton (beanName) of DefaultSingletonBeanRegistry; / / sharedInstance==null performs the following process to create bean / / get the definition information of bean final RootBeanDefinition mbd = getMergedLocalBeanDefinition (beanName) / / get other bean String on which this bean depends [] dependsOn = mbd.getDependsOn (); / / if the dependsOn is not empty, traverse the dependsOn and execute getBean (dep). That is, first create the bean on which this bean depends. If (dependsOn! = null) {for (String dep: dependsOn) {getBean (dep) }} / / if this bean is a single instance Create bean sharedInstance = getSingleton (beanName, ()-> {return createBean (beanName, mbd, args) by doing the following }); / / call the method singletonObject = singletonFactory.getObject () implemented by the anonymous class created above / / call the above createBean (beanName, mbd, args); method. Create bean Object beanInstance = doCreateBean (beanName, mbdToUse, args) / / create and receive an instance object of bean instanceWrapper = createBeanInstance (beanName, mbd, args) / / execute a post processor of type MergedBeanDefinitionPostProcessor. It contains the logic to put @ Autowired,@Value and other information into the injectionMetadataCache, from which the executed populateBean takes values and completes dependency injection applyMergedBeanDefinitionPostProcessors (mbd, beanType, beanName); / / assignment. This includes dependency injection, which assigns populateBean (beanName, mbd, instanceWrapper) to member variables of bean. / / traversal calls the post processor ibp.postProcessAfterInstantiation (bw.getWrappedInstance (), beanName) of type InstantiationAwareBeanPostProcessor . / / this procedure includes AutowiredAnnotationBeanPostProcessor injecting @ Autowired annotated objects into the current bean ibp.postProcessProperties (pvs, bw.getWrappedInstance (), beanName). / / initialize. Execute the Aware interface method, execute the post processor, execute the initialization method exposedObject = initializeBean (beanName, exposedObject, mbd) / / execute the interface method invokeAwareMethods (beanName, bean) of BeanNameAware\ BeanClassLoaderAware\ BeanFactoryAware if the following interface is implemented / / execute the postProcessBeforeInitialization method of the post processor. It contains executing the initialization method wrappedBean = applyBeanPostProcessorsBeforeInitialization (wrappedBean, beanName) specified by @ PostConstruct; / / executing the initialization method. First execute the method that implements the InitializingBean interface, and then execute the initialization method invokeInitMethods (beanName, wrappedBean, mbd) specified by @ Bean; / / execute the applyBeanPostProcessorsAfterInitialization method of the post processor. It contains the post processor / / register destroy method registerDisposableBeanIfNecessary (beanName, bean, mbd) that creates and returns the aop proxy object. / / add bean to the container addSingleton (beanName, singletonObject); after all Bean is created using getBean: check whether all Bean belong to the SmartInitializingSingleton interface If so, execute afterSingletonsInstantiated (); at this point, the study of "what is the Spring IOC initialization execution process" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.