Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Run method of SpringApplication in springboot

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "the run method of SpringApplication in springboot". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Parsing public ConfigurableApplicationContext run (String...) by SpringApplication's run method Args) {/ / construct a task execution observer (Java class for checking time and performance) StopWatch stopWatch = new StopWatch (); / / start execution, record start time stopWatch.start (); / / customize the configuration context where the top-level parent class contains Bean Factory ConfigurableApplicationContext context = null; / / defines an error set (to support reporting startup errors) Collection exceptionReporters = new ArrayList () / / define a headless of awt (set the headless mode, and the system property named java.awt.headless is set to true) configureHeadlessProperty (); / / get a run listener, which mainly listens to the SpringApplication object, (there is only one EventPublishingRunListener inside) SpringApplicationRunListeners listeners = getRunListeners (args); / / calls the start of the listener when the run method of the SpringApplication object is just started (depending on SimpleApplicationEventMulticaster) listeners.starting () Try {/ / construct an application parameter holding class application parameterized ApplicationArguments applicationArguments = new DefaultApplicationArguments (args); / / create and configure Environment (the process gets the input parameters and load the application configuration file), and the configuration environment (Environment) is added to the listener object (SpringApplicationRunListeners) ConfigurableEnvironment environment = prepareEnvironment (listeners, applicationArguments) / / configure bean to scan pring.beaninfo.ignore for attribute reading optional true/false (configured in application file) configureIgnoreBeanInfo (environment); / / print logo, that is, beaninfo.ignore sample image of pringboot Banner printedBanner = printBanner (environment); / / create corresponding Context container to initialize bean according to application type * * context = createApplicationContext () / / get the implementation class exceptionReporters = getSpringFactoriesInstances (SpringBootExceptionReporter.class, new Class [] {ConfigurableApplicationContext.class}, context) from the configuration file; / / prepare to use context before refreshing Context / / correlate prepareContext (context, environment, listeners, applicationArguments, printedBanner) with rain context objects of important components such as SpringApplicationRunListeners, ConfigurableEnvironment, ApplicationArguments, Banner, etc. / / Refresh Context container * / / the key to automatic configuration of spring-boot-starter-* (mybatis, redis, etc.), including core tasks such as spring.factories loading and bean instantiation refreshContext (context); / / processing afterRefresh (context, applicationArguments) after refreshing Context container; / / end of execution, record execution time stopWatch.stop () If (this.logStartupInfo) {new StartupInfoLogger (this.mainApplicationClass) .logStarted (getApplicationLog (), stopWatch) } / / when the Context container is refreshed and released, the listener that accepts the ApplicationStartedEvent event will perform the corresponding operation / / [the Spring container has been refreshed and the application has been started, but CommandLineRunners and ApplicationRunners have not been called yet. Send / / (because ApplicationListener has joined the spring container)] listeners.started (context) directly through the spring container. / trigger the execution of the Context container after refresh to wake up the running thread callRunners (context, applicationArguments);} catch (Throwable ex) {/ / start error report processing handleRunFailure (context, ex, exceptionReporters, listeners); throw new IllegalStateException (ex) } try {/ / Context is started and Runner is forced to publish. Here the listener that accepts the ApplicationStartedEvent event will perform the corresponding operation / / [CommandLineRunners has been called and sent directly through the spring container itself (because ApplicationListener has joined the spring container)] listeners.running (context);} catch (Throwable ex) {/ / starts error report processing handleRunFailure (context, ex, exceptionReporters, null) Throw new IllegalStateException (ex);} / / return Spring container return context;}

The object ConfigurableApplicationContext returned is the applicationContext subclass, which provides more functions than the latter, such as implementing Lifecycle, Closeable interface to better manage the declaration cycle of bean, and other additional functions such as addBeanFactoryPostProcessor,setParent,setId,addApplicationListener,addProtocolResolver.

Create and start the observer

Set the java.awt.headless system variable

Load SpringApplicationRunListener in META-INF/spring.factories under all classpath

The starting method of SpringApplicationRunListener is called sequentially to issue the springboot startup event

Instantiate ApplicationArguments object to get application parameters

Create a ConfigurableEnvironment object environment

Note that webApplicationType controls the type of Environment object created, StandardServletEnvironment.class when SERVLET, StandardReactiveWebEnvironment.class when REACTIVE, and StandardEnvironment.class

Configure the environment object, mainly configure the method parameters into environment-- set properties through configurePropertySources (environment, args) and profiles through configureProfiles (environment, args)

Issue the environmentPrepared event by executing all the environmentPrepared methods of SpringApplicationRunListeners, that is, calling the onApplicationEvent event that implements the ApplicationListener interface ConfigFileApplicationListener

Note that the event gets the collection of factory class instances of type EnvironmentPostProcessor, and adds the ConfigFileApplicationListener instance to the collection. Traversing the instance collection, execute the postProcessEnvironment method once to set the systemEnvironment property and propertySourceList property in the propertySource property of environment, and load the YML configuration file.

That is, bind the current environment to the current springApplication

Put ConfigurationPropertySource into the first in the propertysource of environment

Print Banner

Create a Spring container

Get the concrete exception implementation class from the configuration file

Set the environment of the spring container

When the beanNameGenerator attribute exists, register the beanNameGenerator; with the bean factory when the resourceLoader attribute exists, assign it to the resourceLoader attribute in the context if the context implements GenericApplicationContext, and get its loader to the classLoader attribute in the context if the context implements DefaultResourceLoader

Call back the initialize method of ApplicationContextInitializer to initialize the context, which also detects whether each ApplicationContextInitializer accepts this type of container

Notice that it registers two listeners' ConditionEvaluationReportListener' and 'ServerPortInfoApplicationContextInitializer', in context as well as two bean factory post processors' CachingMetadataReaderFactoryPostProcessor' and 'ConfigurationWarningsPostProcessor' in context

Executes all the contextPrepared methods of SpringApplicationRunListener, but is currently an empty implementation

Register the singleton bean of springApplicationArguments and springBootBanner in context respectively

Get our primarySources and sources load and register into the beanFactory in context, that is, register the main class to beanFactory

Execute all the contextLoaded methods of SpringApplicationRunListener, first determine whether ApplicationListener belongs to ApplicationContextAware, if so, assign the spring container to the listener, then assign the ApplicationListener to the spring container, and then call the onApplicationEvent method of ApplicationListener

Notice that 10 listeners (the value of the listeners attribute) and a bean factory post processor 'PropertySourceOrderingPostProcessor', are registered with context and a singleton bean (SpringBootloggingSystem) is registered

Call the refresh method of AbstractApplicationContext to refresh the Spring container

Set up some initial operations (activate, start date, initialize propertySource), configure the standard context characteristics of the factory, register BeanPostProcessor and BeanFactoryPostProcessor (the former sets bean before and after initialization, and then modify beanFactory or modify beanDefinition or add or initialize bean that is eager to initialize), initialize internationalization files, initialize web containers, instantiate the remaining bean of non-lazy loading, etc.

Call the registerShutdownHook method of AbstractApplicationContext to register a thread that mainly points to the doclose method

Execute all the started methods of SpringApplicationRunListener and issue started events

Call back the callrunners method to get the ApplicationRunner and CommandLineRunner objects from the spring container, then sort them in order, and call their run method in a loop.

Execute all the running methods of SpringApplicationRunListener and issue running events

An exception occurs during the execution of steps 5 to 25. Call the handleRunFailure method to handle different exception states, call listeners.failed (context, exception), and close the spring container.

This is the end of the content of "run method of SpringApplication in springboot". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report