Springboot Start-up

Source: Internet
Author: User

Primarily the Springapplication.run () method, where the preparation environment and the refresh context have a more critical part
The analysis of the project is using the gs-routing-and-filtering under the Complete/gateway-0.0.1-snapshot

1 Get springapplicationrunlisteners, broadcast start event

2 Preparation Environment

3 Print the Spring banner.

4. Create Annotationconfigembeddedwebapplicationcontext

5 Preparing Annotationconfigembeddedwebapplicationcontext

6 Refresh Annotationconfigembeddedwebapplicationcontext

7. Calls made after the refresh, mainly Applicationrunner and Commandlinerunner

8. Publish Completion Events

2 Preparation Environment

Do not listen to the bootstrap context of the applicationenvironmentpreparedevent, that is, Environment getpropertysources () there is bootstrap directly back, Otherwise, create Bootstrapservicecontext ().

When preparing the environment, if no bootstrap context is created and set to apply the context to the parent, some bootstrap need to be used by the bean, when creating the bootstrap In the context of the refresh will be created is instantiated, bootstrap context type is configurableapplicationcontext, after the completion of the preparation of the environment will return standardenvironment, Prepare the environment for completion.

Create Configurableapplicationcontext Configurableapplicationcontext context = bootstrapservicecontext (Environment, Event.getspringapplication ()); use Springapplicationbuilder.run () to create the Configurableapplicationcontext object, This will call Springapplication.run () again. This time prepareenvironment will return directly to the Standardenvironment.createapplicationcontext () that was created before the  Annotationconfigapplicationcontext.preparecontext () invokes Applyinitializers () for various initialization operations before the refresh. The listener publishes the Contextprepared event for Annotationconfigapplicationcontext. Load the bean into the context, load several configuration classes. refreshcontext Tell the subclass to refresh the internal beanfactory, prepare the beanfactory for this context, set the beanfactory callback, register the resolvable dependency, register the default environment beans.factory Processors registers into the context, registers the bean processors when the beans are created, Initializes the Messagesource. Initialize the applicationeventmulticaster. Initializes the special bean for the other special subclass, registering the listener. Instantiates all the remaining singleton objects (not lazy-loaded). Complete Refresh, Initialize lifecycle processor, tell lifecycle processor Onrefresh, release the Contextrefreshedevent event. Reset common introspection caches, Because singleton objects may no longer be able to use these cached metadata. Call runners after refreshing. Call the Springapplicationrunlisteners completion event. Set Bootstrap context as a parent of the application context. Broadcast Applicationenvironmentpreparedevent event. Environment ready 
6 Refresh Annotationconfigembeddedwebapplicationcontext

Look at Abstractapplicationcontext.refresh (), scan the user-defined. class file in the project package, and then make the bean definition and instantiation also in this step. There's a lot of listener in spring, They use Multicaster to broadcast an event to allow special listener to do the specified processing.

准备这个context使用的beanfactoryinvokeBeanFactoryPostProcessors(beanFactory)调用工程处理器在context里注册为bean.扫描用户配置的bean也是在这一步里.ConfigurationClassParser.processConfigurationClass(configurationClass);递归处理ConfigurationClass,和它的父类.ClassPathBeanDefinitionScanner.doScan()扫描项目包,返回BeanDefinitionHolder.默认扫描的路径是@SpringBootApplication的为根目录.这里需要注意的是扫描class文件解析后生成的是BeanDefinition,有了这个就可以创建bean对象,但是此时对象并没有生成.最后发布ContextRefreshedEvent事件刷新后重置spring通用缓存发布ApplicationReadyEvent事件
Code for Abstractapplicationcontext.refresh ():
public void Refresh () throws Beansexception, IllegalStateException {synchronized (this.startupshutdownmonitor) {            Prepare this context for refreshing.            Preparerefresh ();            Tell the subclass to refresh the internal bean factory.            Configurablelistablebeanfactory beanfactory = Obtainfreshbeanfactory ();            Prepare The Bean factory for use with this context.            Preparebeanfactory (beanfactory);                try {//allows post-processing of the Bean factory in context subclasses.                Postprocessbeanfactory (beanfactory);                Invoke factory processors registered as beans in the context.                Invokebeanfactorypostprocessors (beanfactory);                Register Bean processors that intercept bean creation.                Registerbeanpostprocessors (beanfactory);                Initialize message source for this context.                Initmessagesource (); // Initialize Event Multicaster for this context.                Initapplicationeventmulticaster ();                Initialize other special beans in specific context subclasses.                Onrefresh ();                Check for listener beans and register them.                Registerlisteners ();                Instantiate all remaining (Non-lazy-init) singletons.                Finishbeanfactoryinitialization (beanfactory);                Last Step:publish corresponding event.            Finishrefresh (); } catch (Beansexception ex) {if (logger.iswarnenabled ()) {Logger.warn ("Exce                Ption encountered during context initialization-"+" Cancelling refresh attempt: "+ ex);                }//Destroy already created singletons to avoid dangling resources.                Destroybeans ();                Reset ' active ' flag.                CancelRefresh (ex); // Propagate exception to caller.            Throw ex; } finally {//Reset common introspection caches in Spring ' s core, since we//MI            Ght not ever need metadata for singleton beans anymore ... resetcommoncaches (); }        }    }
Some concepts of beandefinition and beans:
Beandefinition describes a bean instance that has a property value, has a constructed parameter value, and provides further information for the specific implementation to use. This is just a minimized interface: The main purpose is to allow beanfactorypostprocessor such as propertyplaceholderconfigurer to introspect and modify the attribute values and other bean metadata. Beanwrapper: The core interface of the JavaBean facility at the spring level is usually not used directly, will be used by beanfactory or DataBinder. Attributeaccessor defines a generic protocol that can get settings metadata from any object. Beanmetadataelement a bean's metadata element is implemented to carry a Configurat Ion source object. Abstractbeandefinition is the concrete, complete beandefinition class of the base class. It's Genericbeandefinition, Decomposition of rootbeandefinition and childbeandefinition public properties. Genericbeandefinition is a one-stop standard bean definition. As with any bean definition, It allows you to specify a class with optional construction parameter values and property values. In addition, the ' ParentName ' attribute from a parent bean definition can be flexibly configured. In general, when using genericbeandefinition, the bean definition to register the user is visible ( A post-processor may operate on it and even have the possibility of reconfiguring the parent name. You can use rootbeandefinition/childbeandefinition when the parent-child relationship is predetermined. Genericbeandefinition is a new bean File configuration property definition class that has been added since 2.5, and is a better alternative to childbeandefinition and rootbeandefinition. Rootbeandefinition indicates at run time , a merged bean definition that supports a particular bean in spring beanfactory. It may be created by multiple source bean definitions that inherit from each other. Typically registered as genericbeandefinition. Essentially, At run time a rootbeandefinition is a unified bean definition view childbeandefinition defines those beans that inherit configuration from the parent classThe. Child bean definition has a fixed dependency on the parent bean definition. Annotatedbeandefinition exposes a note metadata about a class that is defined by the bean, without requiring the class to load. The Annotatedgenericbeandefinition class inherits the Genericbeandefinition abstract class, which supports exposing the annotation metadata information by implementing the Annotatedbeandefinition interface. Note: The Genericbeandefinition variant is primarily used to test the code (you want to operate on annotatedbeandefinition), For example, the implementation class for scan support for spring components (the default class is Scannedgenericbeandefinition, The Annotatedbeandefinition interface is also commonly implemented). Scannedgenericbeandefinition This class does not load the Bean class very early. It tends to get all the relevant metadata from the ". Class" file, using ASM Classreader parsing. Its function is the same as the Annotatedgenericbeandefinition#annotatedgenericbeandefinition (Annotationmetadata), But the type beans that have been scanned and those that have already been registered or found to be other meanings are differentiated by beans.
The process of creating a bean
Run the Spring app, create and refresh a new Applicationcontextspringapplication.run (); Springapplication.refreshcontext ();//Instantiate and invoke all registered beanfactorypostprcessor beans, If there is a definite order in order. Must be called before the Singleton object is instantiated. Abstractapplicationcontext.invokebeanfactorypostprocessors (beanfactory); Postprocessorregistrationdelegate.invokebeandefinitionregistrypostprocessors (PriorityOrderedPostProcessors, registry);//build and validate a configuration model based on a registered config class configrationclasspostprocessor.processconfigbeandefinitions ( registry);//By reading annotations, members, and methods from the source class to process and construct a complete configurationclass. This method can be called multiple times when the relevant source is found, returning the parent class of the processing class, without returning null. Configurationclassparser.doprocessconfigurationclass (Configclass, Sourceclass)/** internal logic: (the order in which classes are loaded) first recursively handles all members ( Include inline), handle all @propertysource annotations, handle all @componentscan annotations, handle all @import annotations, handle all @importresource annotations, and handle individual @bean methods; The default method for processing the interface, and if a parent class handles the parent class, the parent class is found to return the annotation metadata of the parent class and then recursively, without the parent class being processed; *///a scan of the specified base package, returning all registered bean definitions. This method does not register any annotation configuration processors, leaving this to the caller for processing. Classpathbeandefinitionscanner.doscan (basepackages)/** internal logic: Scan package Gets the candidate bean definition; if abstractbeandefinition, Further settings to the bean definition, beyond the scan from the component class to get; if annotatedbeandefinition, the annotations in the metadata are converted to the settings in the bean definition; verifying whether the beanname and related bean definitions need to be registered or in conflict with an existing definition. Create the holder of the bean definition; Whether the holder of the bean needs an agent; *///the classpath for the candidate component (put org.springframework.context.annotation. Classpathbeandefinitionscanner set to trace can output scanned path, ignored resource, set to debug can print authenticated component class or ignored Class)  Classpathbeandefinitionscanner.findcandidatecomponents (basepackage)/** internal logic://Determines whether the given class matches any exclusion filter or at least matches a containing filter. Classpathscanningcandidatecomponentprovider.iscandidatecomponet (Metadatareader)//class according to MetadataReader description,  Create a new scanneedgebericbeandefinition. New Scannedgenericbeandefinition (Metadatareader)//Determines whether the given bean definition has a candidate qualification. The default method implementation checks whether the class is specific (that is, non-abstract or interface).  It also examines whether the class being described is a standalone class, that is, the top-level class or an inline class (Static inner Class) that can be built independently from the encapsulated class. Classpathscanningcandidatecomponentprovider. Iscandidatecomponet (annotatedbeandefinition) *//In the current beanfactory looking for aspectj annotation of the slice bean, Return a list of advisors to indicate their beanfactoryaspectjadvisorsbuilder.buildaspectjadvisors ();
To create an object-dependent calling method

Abstractautowirecapablebeanfactory.instantiatebean (BEANNAME,MBD)

Creating objects

Abstractautowirecapablebeanfactory.initializebean (BEANNAME,BEAN,MBD)

Initializing objects

Abstractautowirecapablebeanfactory.applybeanpostprocessorsbeforeinitialization (ExistingBean,beanName); Aware is set before the process is created

Defaultlistablebeanfactory.preinstantiatesingletons ();

Instantiate all the remaining singleton beans

Start Tomcat

The method of Embeddedwebapplicationcontext.onrefresh () is called when Annotationconfigembeddedwebapplicationcontext refreshes, which creates the container, In this project is to create an inline tomcat.tomcat that will instantiate the Servletcontextinitializer at startup, Zuulfilterinitializer is a subclass of Servletcontextinitializer in this project. The initialization of this class will instantiate the Zuulfilter, including the Simplefilter in the project.

EmbeddedWebApplicationContext.createEmbeddedServletContainer();ContainerBase.startInternal()启动这个组件,实现要求的接口ContainerBase.findChildren()找到这个容器关联的子容器,把子容器放到另一个线程池里执行ContainerBase.StartChild.call();调用子容器StandardEngine.start();StandardHost.startInternal();TomcatStarter.onStartup(classes,servletContext);EmbeddedWebApplicationContext.getServletContextInitializerBeans() 获取embedded Servlet context需要使用的ServletContextInitializer们这里会实例化类型为ServletContextListener的bean,所以ZuulFilterInitializer会在这里被实例化.SimpleFilter会在Initializer里被实例化.这是一些底层处理器的实例化时机,比普通的bean要实例化的早
Springboot Launch Summary

What I care about in Springboot is how the object is created. Scan the class file in refresh to convert to beandefinition. Instantiate when needed. When instantiated, the objects that are dependent are instantiated first, It is often used recursively to iterate through the creation of beans. Finally, some beans that were not created in the initialization are created by Finishbeanfactoryinitialization.

// Instantiate all remaining (non-lazy-init) singletons.finishBeanFactoryInitialization(beanFactory);

Springboot Start-up

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.