Springboot Source Code Analysis-Build Springapplication

Source: Internet
Author: User
Tags addall set set

1 package com.microservice.framework; 2  3 import org.springframework.boot.SpringApplication; 4 Import Org.springframework.boot.autoconfigure.SpringBootApplication; 5  6 @SpringBootApplication 7 public class Myspringaplication {8  9 public     void Run (string[] args) {Ten         SPR Ingapplication sa = new Springapplication (myspringaplication.class);         sa.run (args);     }13 14}

Springboot startup process:

1. Building Springapplication Objects

2. Execute run ()

First, build Springapplication object

1     /**2      * The application context would load beans from the specified sources 3      */4 public     springapplication (Object ... sources) {5         Initialize (sources); 6     }

Description

    • When the class is instantiated, the bean is loaded into the applicationcontext.
    • The entry here is a Class<com.microservice.framework.myspringapplication> object such as Myspringapplication.class
    Private final set<object> sources = new linkedhashset<object> ();    Private Boolean webenvironment;    Private class<?> Mainapplicationclass;    private void Initialize (object[] sources) {        if (sources! = null && sources.length > 0) {            THIS.SOURCES.A Ddall (arrays.aslist (sources));        }        This.webenvironment = Deducewebenvironment ();        Setinitializers ((Collection) getspringfactoriesinstances (                applicationcontextinitializer.class));        Setlisteners ((Collection) getspringfactoriesinstances (Applicationlistener.class));        This.mainapplicationclass = Deducemainapplicationclass ();    }

Steps:

    • Puts the incoming Myspringapplication.class object into the Set collection
    • Determine if it is a Web environment
    • Create a Applicationinitializer list
    • Initializing the Applicationlistener list
    • Initializing the main class Mainapplicationclass

1.1. Put the incoming Myspringapplication.class object into the set set

1.2. Determine if it is a Web environment:

    private static final string[] web_environment_classes = {"Javax.servlet.Servlet",            " Org.springframework.web.context.ConfigurableWebApplicationContext "};    Private Boolean deducewebenvironment () {for        (String classname:web_environment_classes) {            if (! Classutils.ispresent (className, null)) {                return false;            }        }        return true;    }

Description: By looking in classpath for the existence of all classes contained in the web_environment_classes array (actually 2 classes), if present the current program is a Web application, or vice versa.

1.3. Create a Applicationcontextinitializer list

 1 private list<applicationcontextinitializer<?>> initializers; 2 3 public void Setinitializers (4 collection<? extends applicationcontextinitializer<?>> INI Tializers) {5 this.initializers = new arraylist<applicationcontextinitializer<?>> (); 6 this.i Nitializers.addall (initializers); 7} 8 9 private <T> collection<? Extends t> getspringfactoriesinstances (class<t> type) {Ten return getspringfactoriesinstances (type, new Cl Ass<?>[] {});}12-Private <T> collection<? Extends T> getspringfactoriesinstances (class<t> type,14 class<?>[] parametertypes, Object ... ar GS) {ClassLoader ClassLoader = Thread.CurrentThread (). Getcontextclassloader (); +//use names and EN                 Sure unique to protect against duplicates18 set<string> names = new Linkedhashset<string> (19 Springfactoriesloader.loaDfactorynames (type, classLoader)); list<t> instances = new Arraylist<t> (Names.size ()); 21 22 Create instances from the names23 for (String name:names) {try {class<?& Gt                 Instanceclass = Classutils.forname (name, ClassLoader); assert.isassignable (type, instanceclass); 27  constructor<?> Constructor = Instanceclass.getconstructor (parametertypes), T instance = (T) constructor.newinstance (args), Instances.add (instance),}31 catch (Throwa  Ble ex) {new IllegalArgumentException (Cannot instantiate "+ Type +") : "+ name, ex);}35}36 Notoginseng Annotationawareordercomparator.sort (instances); retur N instances;39}

Steps:

    • Call Springfactoriesloader.loadfactorynames (type, classLoader) to get all the names of spring factories, (Here is the full class name for the four Applicationcontextinitializer implementation classes, see below)
    • Creates its object for each spring factories based on the name read. (4 objects created here)
    • Sorts and returns the list of created objects.

where Springfactoriesloader.loadfactorynames (type, ClassLoader) is as follows:

 1/** 2 * The location-to-look for factories. 3 * <p>can is present in multiple JAR files. 4 */5 public static final String factories_resource_location = "Meta-inf/spring.factories"; 6 7/** 8 * Load The fully qualified class names of factory implementations of the 9 * given type from {@va  Lue #FACTORIES_RESOURCE_LOCATION}, using the GIVEN10 * class loader.11 */12 public static list<string> Loadfactorynames (class<?> factoryclass, ClassLoader ClassLoader) {String factoryclassname = Factoryclass . GetName (); try {enumeration<url> urls = (ClassLoader! = null? classloader.getresources (FA             ctories_resource_location): Classloader.getsystemresources (Factories_resource_location)); 17                 list<string> result = new arraylist<string> (); while (Urls.hasmoreelements ()) {19                URL url = urls.nextelement (); 20 Properties Properties = propertiesloaderutils.loadproperties (new Urlresource (URL)); String Factoryclass Names = Properties.getproperty (factoryclassname); Result.addall (Arrays.aslist (stringutils.commadelimited Listtostringarray (Factoryclassnames));}24 return result;25}26 catch (ioexcept                     Ion ex) {illegalargumentexception new ("Unable to load [" + Factoryclass.getname () +28 "] Factories from location [" + Factories_resource_location + "]", ex); 29}30}

Meta-inf/spring-factories

1 # application Context Initializers2 org.springframework.context.applicationcontextinitializer=3 org.springframework.boot.context.configurationwarningsapplicationcontextinitializer,4 org.springframework.boot.context.contextidapplicationcontextinitializer,5 org.springframework.boot.context.config.delegatingapplicationcontextinitializer,6 Org.springframework.boot.context.web.ServerPortInfoApplicationContextInitializer

Description

    • Get all the meta-inf/spring-factories files from all jars. (There is only one under Spring-boot-1.3.0.release.jar here)
    • Iterate through each of the spring-factories files and get its next key to Factoryclass.getname () (Here is the entry

      Org.springframework.context.ApplicationContextInitializer) value (here are the above four Applicationcontextinitializer implementation classes)

The effect of the above four classes:

At this point, the setup applicationcontextinitialize is complete.

Summary: The entire setinitializers is actually initializing the properties of Springapplication list<applicationcontextinitializer<?>> Initializers is a list of ArrayList, with four instances in the list:

    • Examples of Configurationwarningsapplicationcontextinitializer
    • Examples of Contextidapplicationcontextinitializer
    • Delegatingapplicationcontextinitializer instances
    • Serverportinfoapplicationcontextinitializer instances

1.4. Initialize the Applicationlistener list

1     private list<applicationlistener<?>> listeners;     2  3         /** 4      * Sets the {@link applicationlistener}s that'll be applied to the Springapplication 5      * and re Gistered with the {@link ApplicationContext}. 6      * @param listeners the listeners to set 7      */8 public     void Setlisteners (collection<? extends Applicationl Istener<?>> listeners) {9         this.listeners = new arraylist<applicationlistener<?>> (); 10         This.listeners.addAll (listeners);         

Meta-inf/spring-factories

1 # Application Listeners 2 org.springframework.context.applicationlistener= 3 Org.springframework.boot.builder.ParentContextCloserApplicationListener, 4 Org.springframework.boot.context.FileEncodingApplicationListener, 5 Org.springframework.boot.context.config.AnsiOutputApplicationListener, 6 Org.springframework.boot.context.config.ConfigFileApplicationListener, 7 Org.springframework.boot.context.config.DelegatingApplicationListener, 8 Org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener, 9 org.springframework.boot.logging.classpathloggingapplicationlistener,10 Org.springframework.boot.logging.LoggingApplicationListener

The functions of the above eight listener are as follows:

At this point, the entire Setlisteners method is finished, initializing a list collection containing the above 8 Applicationlistener instances.

1.5. Initialize the main class Mainapplicationclass

1     private class<?> mainapplicationclass; 2  3     private class<?> Deducemainapplicationclass () { 4         try {5             stacktraceelement[] StackTrace = new RuntimeException (). Getstacktrace (); 6 for             ( Stacktraceelement stacktraceelement:stacktrace) {7                 if ("Main". Equals (Stacktraceelement.getmethodname ())) {8                     return Class.forName (Stacktraceelement.getclassname ()); 9                 }             }11         }12         catch (ClassNotFoundException ex) {             //Swallow and continue14         }15         return Null;16     }

Description: Gets the main class object where the main () method resides and assigns a value to the Mainapplicationclass property of Springapplication.

At this point, the initialization of the Springapplication object is complete.

Summary: The entire springapplication initialization process, is the initialization of the

    • a sources that contains the myspringapplication.class of the entry parameter . Set<object>
    • Whether a current environment is a Boolean webenvironment of the Web environment
    • A list that contains 4 Applicationcontextinitializer instances
    • A list that contains 8 Applicationlistener instances
    • A class object of the main class where the Main method resides.

Attention:

This article basic reference Http://zhaox.github.io/java/2016/03/22/spring-boot-start-flow complete, the author of the article has been resolved very well, I copy it here again, just to deepen the memory!!!

Http://www.cnblogs.com/java-zhao/p/5540309.html

Springboot Source Code Analysis-Build Springapplication

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.