Package com.microservice.framework; Import org.springframework.boot.SpringApplication; Import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication Public class myspringaplication { publicvoid run (string[] args) { new springapplication (myspringaplication. Class); Sa.run (args);} }
Springboot startup process:
1. Building Springapplication Objects
2. Execute run ()
First, build Springapplication object
/** * The application context would load beans from the specified sources */public c9> springapplication (Object ... sources) { initialize (sources); }
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 Finalset<object> sources =NewLinkedhashset<object>(); Private Booleanwebenvironment; PrivateClass<?>Mainapplicationclass; Private voidInitialize (object[] sources) {if(Sources! =NULL&& sources.length > 0) { This. Sources.addall (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 FinalString[] web_environment_classes = {"Javax.servlet.Servlet", "Org.springframework.web.context.ConfigurableWebApplicationContext" }; Private Booleandeducewebenvironment () { 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
PrivateList<applicationcontextinitializer<?>>initializers; Public voidsetinitializers (Collection<?extendsApplicationcontextinitializer<?>>initializers) { This. initializers =NewArraylist<applicationcontextinitializer<?>>(); This. Initializers.addall (initializers); } Private<T> collection<?extendsT> Getspringfactoriesinstances (class<t>type) { returnGetspringfactoriesinstances (Type,NewClass<?>[] {}); } Private<T> collection<?extendsT> Getspringfactoriesinstances (class<t>type, Class<?>[] parametertypes, Object ... args) {ClassLoader ClassLoader=Thread.CurrentThread (). Getcontextclassloader (); //Use names and ensure unique to protect against duplicatesset<string> names =NewLinkedhashset<string>(Springfactoriesloader.loadfactorynames (Type, classLoader)); List<T> instances =NewArraylist<t>(Names.size ()); //Create instances from the names for(String name:names) {Try{Class<?> Instanceclass =classutils.forname (name, ClassLoader); Assert.isassignable (type, instanceclass); Constructor<?> constructor =Instanceclass.getconstructor (parametertypes); T instance=(T) constructor.newinstance (args); Instances.add (instance); } Catch(Throwable ex) {Throw NewIllegalArgumentException ("Cannot instantiate" + Type + ":" +name, ex); }} annotationawareordercomparator.sort (instances); returninstances; }
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:
/*** The location-to-look for factories. * <p>can is present in multiple JAR files. */ Public Static FinalString factories_resource_location = "Meta-inf/spring.factories"; /*** Load The fully qualified class names of factory implementations of the * given type from {@value#FACTORIES_RESOURCE_LOCATION}, using the given * class loader. */ Public StaticList<string> Loadfactorynames (class<?>Factoryclass, ClassLoader ClassLoader) {String Factoryclassname=Factoryclass.getname (); Try{Enumeration<URL> urls = (ClassLoader! =NULL?classloader.getresources (factories_resource_location): Classloader.getsystemresources (FACTORIES_R esource_location)); List<String> result =NewArraylist<string>(); while(Urls.hasmoreelements ()) {URL URL=urls.nextelement (); Properties Properties= Propertiesloaderutils.loadproperties (Newurlresource (URL)); String Factoryclassnames=Properties.getproperty (factoryclassname); Result.addall (Arrays.aslist (Stringutils.commadelimitedlisttostringarray (Factoryclassnames))); } returnresult; } Catch(IOException ex) {Throw NewIllegalArgumentException ("Unable to load [" + factoryclass.getname () + "] factories from location [" + Factories_resource_location + "]", ex); } }
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
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
PrivateList<applicationlistener<?>>listeners; /*** Sets the {@linkApplicationlistener}s that would be applied to the springapplication * and registered with the {@linkApplicationContext}. * @paramlisteners the listeners to set*/ Public voidSetlisteners (collection<?extendsApplicationlistener<?>>listeners) { This. Listeners =NewArraylist<applicationlistener<?>>(); This. Listeners.addall (listeners); }
Meta-inf/spring-factories
# application Listenersorg.springframework.context.ApplicationListener= Org.springframework.boot.builder.ParentContextCloserApplicationListener, Org.springframework.boot.context.FileEncodingApplicationListener, Org.springframework.boot.context.config.AnsiOutputApplicationListener, Org.springframework.boot.context.config.ConfigFileApplicationListener, Org.springframework.boot.context.config.DelegatingApplicationListener, Org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener, Org.springframework.boot.logging.ClasspathLoggingApplicationListener, 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
PrivateClass<?>Mainapplicationclass; PrivateClass<?>Deducemainapplicationclass () {Try{stacktraceelement[] stackTrace=Newruntimeexception (). Getstacktrace (); for(stacktraceelement stacktraceelement:stacktrace) {if("Main". Equals (Stacktraceelement.getmethodname ())) { returnClass.forName (Stacktraceelement.getclassname ()); } } } Catch(ClassNotFoundException ex) {//Swallow and Continue } return NULL; }
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!!!
>>>>> 3 Springboot Source Code Analysis-Build Springapplication