In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
What is the startup process of SpringBoot? in view of this question, this article introduces in detail the corresponding analysis and answers, hoping to help more partners who want to solve this problem to find a more simple and feasible way.
1.SpringBoot project launch method:
Start the main method in the SpringBoot main class (XXXApplication) in IDE
Start with the mvn spring-boot:run command
Run with java-jar xxx.jar after being packed into a jar package
Put it into a war package and run it in a web container.
The 2.SpringBoot startup process is mainly divided into three steps:
Part I: SpringApplication initialization module, configure some basic environment variables, resources, listeners, constructors
The second part realizes the specific startup scheme of the application, including the monitoring module of the process, loading the configuration environment module and creating the context module.
The third part: automatic configuration module, this module is to realize the automatic configuration of SpringBoot
The main entry of the SpringBoot program is the class annotated with @ SpringBootApplication. In this class, there is a main method that calls the run () method of SpringApplication in the main method. This run () method starts the entire program.
@ SpringBootApplicationpublic class CrmWebApiApplication extends SpringBootServletInitializer {public static void main (String [] args) {SpringApplication.run (CrmWebApiApplication.class, args);}}
The following is the header source code for the @ SpringBootApplication annotation
Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Inherited@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan (excludeFilters = {@ Filter (type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @ Filter (type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class)}) public @ interface SpringBootApplication {
This is a combined annotation, in which the annotated notes mainly have the following functions
@ EnableAutoConfiguration: enable the automatic configuration of SpringBoot. The default configuration of SpringBoot will be loaded automatically when the program starts. If some parameters are configured, it will be appended or overridden when the program is started or called.
@ SpringBootConfiguration: this annotation serves the same purpose as the @ Configuration annotation. It is used to indicate that the annotated class is a configuration class, and one or more methods of the annotated class are added to the Spring container. The name of the instance is the method name by default.
@ ComponentScan: package scanning comments, scanning the classes under the main class package path by default
The code after entering the run () method is as follows:
/ * * Static helper that can be used to run a {@ link SpringApplication} from the * specified sources using default settings and user supplied arguments. * @ param sources the sources to load * @ param args the application arguments (usually passed from a Java main method) * @ return the running {@ link ApplicationContext} * / public static ConfigurableApplicationContext run (Object [] sources, String [] args) {return new SpringApplication (sources) .run (args);}
Here you will create an instance of the SpringApplication class. If you enter the SpringApplication class, you can see that an initialize (sources) method is called in the constructor.
/ * * Create a new {@ link SpringApplication} instance. The application context will load * beans from the specified sources (see {@ link SpringApplication class-level} * documentation for details. The instance can be customized before calling * {@ link # run (String...)}. * @ param sources the bean sources * @ see # run (Object, String []) * @ see # SpringApplication (ResourceLoader, Object...) * / public SpringApplication (Object... Sources) {initialize (sources);}
The source code of Initialize (sources) method is as follows:
@ SuppressWarnings ({"unchecked", "rawtypes"}) private void initialize (Object [] sources) {if (sources! = null & & sources.length > 0) {/ / set sources to the source property of the SpringApplication class, and the source value is only the main class this.sources.addAll (Arrays.asList (sources));} / / determine whether it is a web program, this.webEnvironment = deduceWebEnvironment () / / find the class whose key is ApplicationContextInitializer from the spring.factories file and instantiate it, and then set it to the initializers property of the SpringApplciation class. This process is also to find all the application initializers setInitializers ((Collection) getSpringFactoriesInstances (ApplicationContextInitializer.class)); / / to find the class whose key is ApplicationListener from the spring.factories file and instantiate it and set it to the listeners property of SpringApplication. The process is to find all the application event listeners setListeners ((Collection) getSpringFactoriesInstances (ApplicationListener.class)); / / to find the main class, which is the main class of the SpringBoot project, this.mainApplicationClass = deduceMainApplicationClass ();} 2.1 run method complete code
Go back to the run () method after initialization, and the complete code is as follows:
/ * Run the Spring application, creating and refreshing a new* {@ link ApplicationContext}. * @ param args the application arguments (usually passed from a Java main method) * @ return a running {@ link ApplicationContext} * / public ConfigurableApplicationContext run (String... Args) {StopWatch stopWatch = new StopWatch (); stopWatch.start (); ConfigurableApplicationContext context = null; FailureAnalyzers analyzers = null; configureHeadlessProperty (); / / create application listener SpringApplicationRunListeners listeners = getRunListeners (args); / / start listening on listeners.starting (); try {ApplicationArguments applicationArguments = new DefaultApplicationArguments (args); / / load SpringBoot configuration environment ConfigurableEnvironment, see ConfigurableEnvironment ConfigurableEnvironment environment = prepareEnvironment (listeners,applicationArguments) / print banner Banner printedBanner = printBanner (environment); / / create application context, see 2.3.Create application context context = createApplicationContext (); analyzers = new FailureAnalyzers (context); prepareContext (context, environment, listeners, applicationArguments,printedBanner); refreshContext (context); afterRefresh (context, applicationArguments); listeners.finished (context, null); stopWatch.stop () If (this.logStartupInfo) {new StartupInfoLogger (this.mainApplicationClass) .logStarted (getApplicationLog (), stopWatch);} return context;} catch (Throwable ex) {handleRunFailure (context, listeners, analyzers, ex); throw new IllegalStateException (ex);}} 2.2 configure ConfigurableEnvironment
The process of loading the SpringBoot configuration environment ConfigurableEnvironment is as follows:
Private ConfigurableEnvironment prepareEnvironment (SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) {/ / Create and configure the environment ConfigurableEnvironment environment = getOrCreateEnvironment (); configureEnvironment (environment, applicationArguments.getSourceArgs ()); listeners.environmentPrepared (environment) If (! this.webEnvironment) {environment = new EnvironmentConverter (getClassLoader ()) .convertToStandardEnvironment IfNecessary (environment);} return environment;}
In the process of loading the configuration environment, it will determine whether the web container starts, and if it is the container startup, it will load StandardServletEnvironment.
Private ConfigurableEnvironment getOrCreateEnvironment () {if (this.environment! = null) {return this.environment;} if (this.webEnvironment) {return new StandardServletEnvironment ();} return new StandardEnvironment ();}
The inheritance relationship of the StandardServletEnvironment class is as follows, StandardServletEnvironment
The PropertyResolver interface is used to parse the properties of any underlying source, and the configuration environment is added to the listener object SpringApplicationRunListeners after the configuration is loaded.
2.3 create an application context
Then the application context object is created as follows:
Protected ConfigurableApplicationContext createApplicationContext () {Class contextClass = this.applicationContextClass; if (contextClass = = null) {try {contextClass = Class.forName (this.webEnvironment? DEFAULT_WEB_CONTEXT_CLASS: DEFAULT_CONTEXT_CLASS) } catch (ClassNotFoundException ex) {throw new IllegalStateException ("Unable create a default ApplicationContext,"+" please specify an ApplicationContextClass ") Ex) } return (ConfigurableApplicationContext) BeanUtils.instantiate (contextClass);}
The method explicitly acquires the application context object first, and then loads the default environment configuration if the object is empty. To determine whether it is webEnvironment or not, the default selection is AnnotationConfigApplicationContext (annotation context, load bean by scanning seconds), and then instantiate the application context object through BeanUtils and return it. The inheritance relationship of ConfigurableApplicationContext class is as follows:
Here I recommend another blog post. If you don't know much about ConfigurableApplicationContext, you can take a look at it, https://juejin.im/post/5d72055f5188256bab4c0b6d.
Back in the run () method, the prepareContext () method is called to associate components such as environment, listeners,applicationArguments, printedBanner, etc., with the context object
Private void prepareContext (ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {context.setEnvironment (environment); postProcessApplicationContext (context); applyInitializers (context); listeners.contextPrepared (context) If (this.logStartupInfo) {logStartupInfo (context.getParent () = = null); logStartupProfileInfo (context);} / / Add boot specific singleton beans context.getBeanFactory () .registerSingleton ("springApplicationArguments", applicationArguments) If (printedBanner! = null) {context.getBeanFactory (). RegisterSingleton ("springBootBanner", printedBanner);} / / Load the sources Set sources = getSources (); Assert.notEmpty (sources, "Sources must not be empty"); load (context, sources.toArray (new Object [sources.size ()])) Listeners.contextLoaded (context);}
The refreshContext () method is then called to actually call the relevant methods within org.springframework.context.support.AbstractApplicationContext.refresh (). This method will automatically configure redis,mybatis, etc., including loading of spring.factories, instantiation of bean, execution of BenFactoryPostProcessor interface, execution of BeanPostProcessor interface, parsing of conditional annotations, initialization of internationalization function, etc.
After the refreshContext () method is executed, the afterRefresh method is executed, and when the run () method is executed, the Spring container is initialized.
Protected void afterRefresh (ConfigurableApplicationContext context, ApplicationArguments args) {callRunners (context, args);} private void callRunners (ApplicationContext context, ApplicationArguments args) {List runners = new ArrayList (); runners.addAll (context.getBeansOfType (ApplicationRunner.class). Values ()); runners.addAll (context.getBeansOfType (CommandLineRunner.class). Values ()) AnnotationAwareOrderComparator.sort (runners); for (Object runner: new LinkedHashSet (runners)) {if (runner instanceof ApplicationRunner) {callRunner ((ApplicationRunner) runner, args) } if (runner instanceof CommandLineRunner) {callRunner ((CommandLineRunner) runner, args) } private void callRunner (ApplicationRunner runner, ApplicationArguments args) {try {(runner) .run (args);} catch (Exception ex) {throw new IllegalStateException ("Failed to execute ApplicationRunner", ex) }} private void callRunner (CommandLineRunner runner, ApplicationArguments args) {try {(runner) .run (args.getSourceArgs ());} catch (Exception ex) {throw new IllegalStateException ("Failed to execute CommandLineRunner", ex) }} the answers to the questions about the startup process of SpringBoot are shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
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.