In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What is the startup source code of Springboot Code? in view of this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.
The process to start the project:
(1) new SpringApplication
Configure the source and web environment
Create initialization constructors and application listeners
Configure the class where the main method of the application resides
(II) part 12 of run
1. Get and start the listener
Initialize timing stopWatch, launch context bootstrapContext, set system parameter headless
Initialize listeners list SpringApplicationRunListeners
Publish springboot start event (filter out 4 listeners for ApplicationStartingEvent events from applicationListeners and start them)
two。 Prepare the environment
Assembly command line parameter applicationArguments (4 propertySource loaded in object)
Prepare the environment in which the application runs ConfigurableEnvironment (filter out 6 listeners for ApplicationEnvironmentPreparedEvent events from applicationListeners and start them. The association in the listener starts some post-processors to process data, the ultimate goal is to prepare for the application environment)
3. Print banner
Method: public ConfigurableApplicationContext run (String... Args) {/ / 1, StopWatch is simply regarded as a stop watch mechanism to save the record information of stop. / / initialize a timer and start timing StopWatch stopWatch = new StopWatch (); stopWatch.start (); / initialize startup context DefaultBootstrapContext bootstrapContext = this.createBootstrapContext (); ConfigurableApplicationContext context = null; / / 2, configureHeadlessProperty configure headless mode, which is a situation where the system lacks display devices, keyboards and mouse peripherals. This.configureHeadlessProperty () / / 3. SpringApplicationListeners initializes the listener list for the SpringApplicationRunListener interface implementation collection (create SpringApplicationRunListener initialization constructor) / / it can be understood that this interface needs to call back these listener / / debug when spring starts the whole process, and gets an EventPublishingRunListener (all applicationListener are associated in the RunListener constructor method) This is the observed SpringApplicationRunListeners listeners = this.getRunListeners (args) used to trigger the publishEvent. / / launch EventPublishingRunListener to filter and launch relevant Listener listeners.starting (bootstrapContext, this.mainApplicationClass); try {ApplicationArguments applicationArguments = new DefaultApplicationArguments (args); / / 4. ConfigurableEnvironment is the configuration environment object, so simply understand that all configuration information is summarized in this object: ConfigurableEnvironment environment = this.prepareEnvironment (listeners, bootstrapContext, applicationArguments); this.configureIgnoreBeanInfo (environment) / / 5. Banner is the screen banner that we often output in the console. You can use pictures or text to replace Banner printedBanner = this.printBanner (environment); = > / / 6, ConfigurableApplicationContext according to webApp. The context object constructed by Type context = this.createApplicationContext (); context.setApplicationStartup (this.applicationStartup); / / 7. Next to the first step of the critical step: prepareContext, the container preparation phase, all initializers logic will be executed and initialization preparation will be done. This.prepareContext (bootstrapContext, context, environment, listeners, applicationArguments, printedBanner); / 8, refreshContext, which can be understood as container initialization nodes, will perform the creation and instantiation of bean. This.refreshContext (context); / / 9, afterRefresh, container post-processing, you can see that the implementation classes of ApplicationRunner and CommandLineRunner will be found and executed. However, from the 2.x version, it seems that this method is an empty method, applicationRun and commandRun moved to the last boot. This.afterRefresh (context, applicationArguments); / / 10, and then print the startup time stopWatch.stop () according to stopwatch; if (this.logStartupInfo) {(new StartupInfoLogger (this.mainApplicationClass)) .logStarted (this.getApplicationLog (), stopWatch);} listeners.started (context) / 11. The implementation classes this.callRunners (context, applicationArguments) of ApplicationRunner and CommandLineRunner are called here;} catch (Throwable var10) {this.handleRunFailure (context, var10, listeners); throw new IllegalStateException (var10);} try {listeners.running (context); return context } catch (Throwable var9) {this.handleRunFailure (context, var9, (SpringApplicationRunListeners) null); throw new IllegalStateException (var9);}}
Let's start the creation and preparation of context.
Context = this.createApplicationContext (); protected ConfigurableApplicationContext createApplicationContext () {return this.applicationContextFactory.create (this.webApplicationType);} public interface ApplicationContextFactory {ApplicationContextFactory DEFAULT = (webApplicationType)-> {try {switch (webApplicationType) {case SERVLET: return new AnnotationConfigServletWebServerApplicationContext (); case REACTIVE: return new AnnotationConfigReactiveWebServerApplicationContext () Default: return new AnnotationConfigApplicationContext ();}} catch (Exception var2) {throw new IllegalStateException ("Unable create a default ApplicationContext instance, you may need a custom ApplicationContextFactory", var2);}}; ConfigurableApplicationContext create (WebApplicationType webApplicationType);....}
The above code can create an AnnotationConfigServletWebServerApplicationContext object through webApplicationTyep (that is, SERVLET). During the object creation process, the property values of the parent class are initialized, among which there are three key values, reader, scanner and beanFactory in the parent class. The hierarchy of the following object needs to be known.
/ * both reader and scanner are assigned in the constructor * * / public class AnnotationConfigServletWebServerApplicationContext extends ServletWebServerApplicationContext implements AnnotationConfigRegistry {private final AnnotatedBeanDefinitionReader reader; private final ClassPathBeanDefinitionScanner scanner; private final Set requiredType = GenericTypeResolver.resolveTypeArgument (initializer.getClass (), ApplicationContextInitializer.class); Assert.isInstanceOf (requiredType, context, "Unable to call initializer."); initializer.initialize (context) }} / / load the class com.learning.demo.DemoApplication startup class protected void load (ApplicationContext context, Object [] sources) {if (logger.isDebugEnabled ()) {logger.debug ("Loading source" + StringUtils.arrayToCommaDelimitedString (sources));} BeanDefinitionLoader loader = this.createBeanDefinitionLoader (this.getBeanDefinitionRegistry (context), sources) If (this.beanNameGenerator! = null) {loader.setBeanNameGenerator (this.beanNameGenerator);} if (this.resourceLoader! = null) {loader.setResourceLoader (this.resourceLoader);} if (this.environment! = null) {loader.setEnvironment (this.environment);} loader.load ();}
Debug, where the load method can follow up registerBean (startup class) from multiple layers to AnnotatedBeanDefinitionReader
Public void registerBean (Class beanClass) {this.doRegisterBean (beanClass, (String) null, (Class []) null, (Supplier) null, (BeanDefinitionCustomizer []) null);}
There are also two methods for listeners.*, which are the same as the previous listeners.starting (), and provide a recently sorted class diagram (to understand the relationship between the Runlistener and listener classes)
/ / 6. ConfigurableApplicationContext according to webApp... The context object constructed by Type context = this.createApplicationContext (); context.setApplicationStartup (this.applicationStartup); / / 7. Next to the first step of the critical step: prepareContext, the container preparation phase, all initializers logic will be executed and initialization preparation will be done. This.prepareContext (bootstrapContext, context, environment, listeners, applicationArguments, printedBanner); = > / / 8, refreshContext, can be understood as container initialization nodes, which will perform the creation and instantiation of bean. This.refreshContext (context); / / 9, afterRefresh, container post-processing, you can see that the implementation classes of ApplicationRunner and CommandLineRunner will be found and executed. However, from the 2.x version, it seems that this method is an empty method, applicationRun and commandRun moved to the last boot. This.afterRefresh (context, applicationArguments); / / 10, and then print the startup time stopWatch.stop () according to stopwatch; if (this.logStartupInfo) {(new StartupInfoLogger (this.mainApplicationClass)) .logStarted (this.getApplicationLog (), stopWatch);} listeners.started (context) / / 11. The implementation classes this.callRunners (context, applicationArguments) of ApplicationRunner and CommandLineRunner are called here
RefreshContext () is the core part of the whole Run method
/ * refresh application context * * @ param context * / private void refreshContext (ConfigurableApplicationContext context) {/ / register a shutdown hook that will trigger when jvm stops Then execute some exit logic if (this.registerShutdownHook) {try {/ / add: Runtime.getRuntime () .addShutdownHook () / remove: Runtime.getRuntime () .exit (this.shutdownHook) context.registerShutdownHook () } catch (AccessControlException ex) {/ / Not allowed in some environments. }} / / ApplicationContext actually starts the phase of initializing the container and creating the bean refresh ((ApplicationContext) context);} protected void refresh (ApplicationContext applicationContext) {Assert.isInstanceOf (ConfigurableApplicationContext.class, applicationContext); refresh ((ConfigurableApplicationContext) applicationContext) } protected void refresh (ConfigurableApplicationContext applicationContext) {applicationContext.refresh ();}
Call the refresh () method of the application context object, and then I go to the ConfigurableApplicationContext class to take a look at this method
Public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {void refresh () throws BeansException, IllegalStateException;}
This is an interface, and this class is in the spring framework, not springboot, it has three implementation classes
AbstractApplicationContext is an abstract class, and the other two classes inherit it. Let's take a look at the code for this abstract class:
@ Override public void refresh () throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {StartupStep contextRefresh = this.applicationStartup.start ("spring.context.refresh"); / / first step: prepare to update the preparatory work prepareRefresh () / / step 2: get the context BeanFactory ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory (); / / step 3: prepare for BeanFactory prepareBeanFactory (beanFactory) Try {/ / step 4: allow post-processing postProcessBeanFactory (beanFactory) of the bean factory in the context subclass; StartupStep beanPostProcess = this.applicationStartup.start ("spring.context.beans.post-process") / / step 5: invoke the factory BeanFactoryPostProcessor invokeBeanFactoryPostProcessors (beanFactory) registered as bean in the context; / / step 6: register the interceptor created by bean registerBeanPostProcessors (beanFactory) BeanPostProcess.end (); / / step 7: initialize MessageSource (internationalization related) initMessageSource () / / step 8: initialize the container event broadcaster (used to publish events) initApplicationEventMulticaster (); / / step 9: initialize some special bean onRefresh () / / step 10: register all listeners with the event broadcaster created in the previous two steps registerListeners (); / / step 11: end the initialization of bean (mainly instantiate all singleton BeanDefinition) finishBeanFactoryInitialization (beanFactory) / / step 12: afterRefresh (context refresh is complete, publish the corresponding event) finishRefresh () } catch (BeansException ex) {if (logger.isWarnEnabled ()) {logger.warn ("Exception encountered during context initialization -" + "cancelling refresh attempt:" + ex) } / / Destroy already created singletons to avoid dangling resources. DestroyBeans (); / / Reset 'active' flag. CancelRefresh (ex); / / Propagate exception to caller. Throw ex;} finally {/ / Reset common introspection caches in Spring's core, since we / / might not ever need metadata for singleton beans anymore... ResetCommonCaches (); contextRefresh.end ();}
There are a lot of steps here, and the main bean of the context object is also handled here. For specific instructions, please see the comments. The fresh method is the part of the SpringFrameWork (no longer detailed).
/ / 6. ConfigurableApplicationContext according to webApp... The context object constructed by Type context = this.createApplicationContext (); context.setApplicationStartup (this.applicationStartup); / / 7. Next to the first step of the critical step: prepareContext, the container preparation phase, all initializers logic will be executed and initialization preparation will be done. This.prepareContext (bootstrapContext, context, environment, listeners, applicationArguments, printedBanner); / 8, refreshContext, which can be understood as container initialization nodes, will perform the creation and instantiation of bean. This.refreshContext (context); = > / / 9, afterRefresh, container post-processing, you can see that the implementation classes of ApplicationRunner and CommandLineRunner will be found and executed. However, from the 2.x version, it seems that this method is an empty method, applicationRun and commandRun moved to the last boot. This.afterRefresh (context, applicationArguments); = > / / 10, and then print the startup time stopWatch.stop () according to stopwatch; if (this.logStartupInfo) {(new StartupInfoLogger (this.mainApplicationClass)) .logStarted (this.getApplicationLog (), stopWatch);} listeners.started (context) / / 11. The implementation classes this.callRunners (context, applicationArguments) of ApplicationRunner and CommandLineRunner are called here
AfterRefresh () is an extension of the method refresh (), which is temporarily empty.
StopWatch.stop () prints out the startup time according to the stopwatch, and the project has been started.
* the run method mainly does the following:
Issue a startup end event
Execute the run method that implements ApplicationRunner and CommandLineRunner
Publish an application started (ApplicationStartedEvent) event
Combined with the two pictures shared online, you can clearly review the overall process:
The answer to the question about the startup source code of Springboot Code is shared here. I hope the above content can be of some help to everyone. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.
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.