Up posture: Spring Boot 2.x start the whole process of source code analysis

Source: Internet
Author: User
Tags addall log log throwable

"Spring Boot 2.x start the whole process of source analysis (a) Import class analysis" We analyzed the Spring boot entry class Springapplication source code, and know its construction principle, this we continue to analyze its core run method.

[TOC]

Springapplication instance Run method running procedure

The above analysis of the Springapplication instance object construction method initialization process, the following continue to see the Springapplication object of the Run method of the source code and running process.

Public Configurableapplicationcontext run (String ... args) {///1, create and start the timing monitoring class StopWatch StopWatch = new StopWatch ();    Stopwatch.start ();    2. Initialize the application context and Exception Report Collection Configurableapplicationcontext context = null;    collection<springbootexceptionreporter> exceptionreporters = new arraylist<> ();    3, set the System property ' java.awt.headless ' value, the default value is: True Configureheadlessproperty ();    4. Create all Spring run listeners and publish app launch events springapplicationrunlisteners listeners = getrunlisteners (args);    Listeners.starting ();                try {//5, initialize default application parameter class applicationarguments applicationarguments = new Defaultapplicationarguments (        args); 6. Prepare the Spring environment according to the running listener and application parameters configurableenvironment environment = prepareenvironment (listeners, a        pplicationarguments);        Configureignorebeaninfo (Environment);        7, create Banner printing class Banner Printedbanner = Printbanner (Environment); 8. Create an Application context: Context = CreateApplicationContext ();        9. Prepare exception reporter Exceptionreporters = getspringfactoriesinstances (springbootexceptionreporter.c        Lass, new class[] {Configurableapplicationcontext.class}, context);        10. Prepare application Context Preparecontext (contexts, environment, listeners, applicationarguments, Printedbanner);        11, refresh the application context Refreshcontext (contextual);        12, Application context refresh post processing AfterRefresh (context, applicationarguments);        13, stop the timing monitoring class stopwatch.stop ();                    14. Output log execution main class name, time information if (this.logstartupinfo) {new Startupinfologger (This.mainapplicationclass)        . logstarted (Getapplicationlog (), stopWatch);        }//15, publish application context start completion event listeners.started (context);    16. Execute all Runner callrunners (context, applicationarguments);        } catch (Throwable ex) {handlerunfailure (context, ex, exceptionreporters, listeners);    throw new IllegalStateException (ex); }   try {//17, publish application Context Ready Event listeners.running (context);        } catch (Throwable ex) {handlerunfailure (context, ex, exceptionreporters, NULL);    throw new IllegalStateException (ex); }//18, return to application context return context;}

Therefore, we can break down the start process of the Run method by following several steps.

1. Create and start the timing monitoring class
StopWatch stopWatch = new StopWatch();stopWatch.start();

Take a look at the relevant source code for the timing monitoring class StopWatch:

public void start() throws IllegalStateException {    start("");}public void start(String taskName) throws IllegalStateException {    if (this.currentTaskName != null) {        throw new IllegalStateException("Can‘t start StopWatch: it‘s already running");    }    this.currentTaskName = taskName;    this.startTimeMillis = System.currentTimeMillis();}

The name of the current task is recorded first, the default is an empty string, and then the start time of the current Spring boot app start is recorded.

2. Initialize the application context and Exception Report collection
ConfigurableApplicationContext context = null;Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
3. Set System Properties java.awt.headlessThe value
configureHeadlessProperty();

Set the default value to: True,java.awt.headless = True what is the effect?

For a Java server, some graphical elements, such as map creation or graphics and graphs, are often processed. These APIs basically always need to run a x-server in order to be able to use the AWT (abstract window Toolkit, abstracted Windows toolset). However, running an unnecessary x-server is not a good way to manage it. Sometimes you can't even run x-server, so the best solution is to run the headless server for simple image processing.

Reference: www.cnblogs.com/princessd8251/p/4000016.html

4. Create all Spring run listeners and publish app launch events
SpringApplicationRunListeners listeners = getRunListeners(args);listeners.starting();

Look at the source code for creating the Spring Run Listener:

private SpringApplicationRunListeners getRunListeners(String[] args) {    Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };    return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances(            SpringApplicationRunListener.class, types, this, args));}SpringApplicationRunListeners(Log log,        Collection<? extends SpringApplicationRunListener> listeners) {    this.log = log;    this.listeners = new ArrayList<>(listeners);}

Creating the logic is the same as before instantiating the initializer and listener, calling a getSpringFactoriesInstances method to get the configured listener name and instantiating all classes.

Springapplicationrunlistener all listeners are configured in spring-boot-2.0.3.RELEASE.jar!/META-INF/spring.factories this configuration file.

# Run Listenersorg.springframework.boot.SpringApplicationRunListener=org.springframework.boot.context.event.EventPublishingRunListener
5. Initialize default application parameter class
ApplicationArguments applicationArguments = new DefaultApplicationArguments(        args);
6. Prepare the Spring environment according to the operation Listener and application parameters
ConfigurableEnvironment environment = prepareEnvironment(listeners,        applicationArguments);configureIgnoreBeanInfo(environment);

Below we mainly look at the source of the preparation environment prepareEnvironment :

private ConfigurableEnvironment prepareEnvironment(        SpringApplicationRunListeners listeners,        ApplicationArguments applicationArguments) {    // 6.1) 获取(或者创建)应用环境    ConfigurableEnvironment environment = getOrCreateEnvironment();    // 6.2) 配置应用环境    configureEnvironment(environment, applicationArguments.getSourceArgs());    listeners.environmentPrepared(environment);    bindToSpringApplication(environment);    if (this.webApplicationType == WebApplicationType.NONE) {        environment = new EnvironmentConverter(getClassLoader())                .convertToStandardEnvironmentIfNecessary(environment);    }    ConfigurationPropertySources.attach(environment);    return environment;}

6.1) get (or create) the application environment

private ConfigurableEnvironment getOrCreateEnvironment() {    if (this.environment != null) {        return this.environment;    }    if (this.webApplicationType == WebApplicationType.SERVLET) {        return new StandardServletEnvironment();    }    return new StandardEnvironment();}

This is divided into standard Servlet environments and standard environments.

6.2) Configure the application environment

protected void configureEnvironment(ConfigurableEnvironment environment,        String[] args) {    configurePropertySources(environment, args);    configureProfiles(environment, args);}

This is divided into the following two steps to configure the application environment.

    • Configure Property sources
    • Configure Profiles

All property sources configurations and profiles configurations are mainly handled here.

7. Create Banner Print Class
Banner printedBanner = printBanner(environment);

This is the processing class for printing Banner, this is nothing to say.

8. Create an Application context
context = createApplicationContext();

Look createApplicationContext() at the source of the method:

  protected Configurableapplicationcontext createapplicationcontext () {class<?> Contextclass =    This.applicationcontextclass;                if (Contextclass = = null) {try {switch (this.webapplicationtype) {case SERVLET:                Contextclass = Class.forName (Default_web_context_class);            Break                Case reactive:contextclass = Class.forName (Default_reactive_web_context_class);            Break            Default:contextclass = Class.forName (Default_context_class); }} catch (ClassNotFoundException ex) {throw new IllegalStateException ("Unab                    Le create a default ApplicationContext, "+" Specify an Applicationcontextclass ",        ex); }} return (Configurableapplicationcontext) Beanutils.instantiateclass (Contextclass);}  

It is actually initializing different context application classes based on different application types.

9. Prepare Exception Reporter
exceptionReporters = getSpringFactoriesInstances(        SpringBootExceptionReporter.class,        new Class[] { ConfigurableApplicationContext.class }, context);

The logic, like the one before instantiating the initializer and listener, is to invoke a getSpringFactoriesInstances method to get the configured exception class name and instantiate all exception-handling classes.

The Exception report processing class is configured in spring-boot-2.0.3.RELEASE.jar!/META-INF/spring.factories this configuration file.

# Error Reportersorg.springframework.boot.SpringBootExceptionReporter=org.springframework.boot.diagnostics.FailureAnalyzers
10. Prepare the application context
prepareContext(context, environment, listeners, applicationArguments,        printedBanner);

Look prepareContext() at the source of the method:

private void Preparecontext (configurableapplicationcontext context, configurableenvironment environment, SPRINGAPPL Icationrunlisteners listeners, Applicationarguments applicationarguments, Banner printedbanner) {//10.1) Bind the environment to the top    Below context.setenvironment (environment);    10.2) configuration context of the bean generator and the resource Loader postprocessapplicationcontext (context);    10.3) Apply all initializers applyinitializers (context) for contexts;    10.4) Trigger the Contextprepared event method of all Springapplicationrunlistener listeners listeners.contextprepared (context);        10.5) Record the startup log if (This.logstartupinfo) {Logstartupinfo (context.getparent () = = null);    Logstartupprofileinfo (context); }//10.6) Register two special Singleton Bean Context.getbeanfactory (). Registersingleton ("Springapplicationarguments", Applicat    ionarguments);    if (Printedbanner! = null) {context.getbeanfactory (). Registersingleton ("Springbootbanner", Printedbanner);    }//10.7) load all resources set<object> sources = getallsources (); ASsert.notempty (sources, "sources must not being empty");    Load (context, Sources.toarray (new object[0])); 10.8) Contextloaded event method that triggers all Springapplicationrunlistener listeners listeners.contextloaded (context);}
11. Refresh the application context
refreshContext(context);

This is mainly to refresh the application context of Spring, the source code is as follows, not detailed description.

private void refreshContext(ConfigurableApplicationContext context) {    refresh(context);    if (this.registerShutdownHook) {        try {            context.registerShutdownHook();        }        catch (AccessControlException ex) {            // Not allowed in some environments.        }    }}
12. Apply context Refresh post processing
afterRefresh(context, applicationArguments);

Look at this method of the source code is empty, can now do some custom post-processing operations.

/** * Called after the context has been refreshed. * @param context the application context * @param args the application arguments */protected void afterRefresh(ConfigurableApplicationContext context,        ApplicationArguments args) {}
13. Stop Timing Monitoring class
stopWatch.stop();
public void stop() throws IllegalStateException {    if (this.currentTaskName == null) {        throw new IllegalStateException("Can‘t stop StopWatch: it‘s not running");    }    long lastTime = System.currentTimeMillis() - this.startTimeMillis;    this.totalTimeMillis += lastTime;    this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime);    if (this.keepTaskList) {        this.taskList.add(this.lastTaskInfo);    }    ++this.taskCount;    this.currentTaskName = null;}

The timer listener stops and counts some task execution information.

14. Output logging execution main class name, time information
if (this.logStartupInfo) {    new StartupInfoLogger(this.mainApplicationClass)            .logStarted(getApplicationLog(), stopWatch);}
15. Publish application context Start completion events
listeners.started(context);

The started event method that triggers all Springapplicationrunlistener listeners.

16. Perform all Runner running
callRunners(context, applicationArguments);
private void callRunners(ApplicationContext context, ApplicationArguments args) {    List<Object> 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);        }    }}

Execute all ApplicationRunner and both CommandLineRunner of the runtimes, without detailed deployment.

17. Publish application Context-ready events
listeners.running(context);

The running event method that triggers all Springapplicationrunlistener listeners.

18. Return to Application context
return context;
Summarize

Spring boot to start the whole process of source code analysis to this, the analysis of spring source is really a painful process, I hope to provide you with a little reference and ideas, but also hope to be Spring Boot learning on the road friends a little harvest.

Source analysis is not easy, like + forward support!

Up posture: Spring Boot 2.x start the whole process of source code analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.