Spring Boot series--spring boot how to boot

Source: Internet
Author: User
Tags throwable
Spring Boot boot process

The Spring Boot series-5 minutes to build an app-explains how to quickly create a spring boot project and run it. Although the steps are simple and the developers save a lot of repetitive configuration work, the underlying implementation is not so simple.

In this article, we'll look at the entry class Tutorialapplication to see how spring boot starts.

Annotations

Spring boot knows that there needs to be an entry class, which is the tutorialapplication in this example, and this class must have a @springbootapplication annotation on it.

By clicking into the note, we can see that it is a composite annotation, including @springbootconfiguration, @EnableAutoConfiguration, and @componentscan.

/** * Indicates a {@link configuration configuration} class that declares one or more * {@link Bean @Bean} methods and ALS o Triggers {@link enableautoconfiguration * auto-configuration} and {@link Componentscan component scanning}. This is a convenience * annotation of equivalent to declaring {@code @Configuration}, * {@code @EnableAutoConfigurati on} and {@code @ComponentScan}. * * @author Phillip Webb * @author Stephane Nicoll * @since 1.2.0 * * @Target (Elementtype.type) @Retention (retentionpolicy.ru Ntime) @Documented @inherited@springbootconfiguration@enableautoconfiguration@componentscan (excludeFilters = {@ Filter (type = filtertype.custom, classes = Typeexcludefilter.class), @Filter (type = filtertype.custom, classes = Auto Configurationexcludefilter.class)}) public @interface springbootapplication {/** * Exclude specific Auto-configurati    On classes such that they would never be applied. * @return The classes to exclude */@AliasFor (annotation = EnableautoconfiguRation.class) class<?>[] Exclude () default {};    /** * Exclude specific auto-configuration class names such that they would never be * applied. * @return The class names to exclude * @since 1.3.0 */@AliasFor (annotation = enableautoconfiguration.class) Str   Ing[] Excludename () default {}; /** * Base packages to scan for annotated.    Use {@link #scanBasePackageClasses} * For a type-safe alternative to string-based the package names. * @return Base packages to scan * @since 1.3.0 */@AliasFor (annotation = componentscan.class, attribute = "Basepac   Kages ") string[] Scanbasepackages () default {}; /** * Type-safe alternative to {@link #scanBasePackages} for specifying the packages to * scan for annotated Compone Nts.    The package of each class specified would be scanned. * <p> * Consider creating a special No-op marker class or interface in each package that * serves no purpose o Ther than being referenced by this attribute.    * @return Base packages to scan * @since 1.3.0 */@AliasFor (annotation = componentscan.class, attribute = "bas Epackageclasses ") class<?>[] scanbasepackageclasses () default {};}

@SpringBootConfiguration

The bottom of the note is actually a @configuration annotation. Be familiar with spring's development milestones and know that this is the configuration form of Java CONFIG.

This annotation is decorated to indicate that the class is a configuration class.

@EnableAutoConfiguration

This annotation is actually a composite annotation.

/** * Enable Auto-configuration of the Spring application Context, attempting to guess and * Configure beans Likely to need. Auto-configuration classes is usually * applied based on your classpath and what beans you have defined. For example, if you * has {@code Tomcat-embedded.jar} on your classpath is likely to want a * {@link Tomcatservletwe Bserverfactory} (unless you have defined your own * {@link servletwebserverfactory} beans). * <p> * When using {@link springbootapplication}, the auto-configuration of the context is * automatically enabled a nd Adding this annotation have therefore no additional effect. * <p> * Auto-configuration tries to be as intelligent as possible and would back-away as you * Define more of your OW N Configuration.  You can all manually {@link #exclude ()} any * configuration, never want to apply (use {@link #excludeName ()} if You don ' t * has access to them). You can also exclude them via the * {@code spring.autoconfigure. Exclude} property. Auto-configuration is all applied * after user-defined beans has been registered. * <p> * The package of this class is annotated with {@code @EnableAutoConfiguration}, * usually via {@code @Spri Ngbootapplication}, have specific significance and is often used * as a ' default '. For example, it is used when scanning for {@code @Entity} classes. * It is generally recommended so you place {@code @EnableAutoConfiguration} (if you ' re * not using {@code @SpringBootApp Lication}) in a, root package so, all sub-packages * and classes can is searched. * <p> * auto-configuration classes is regular Spring {@link configuration} beans. They is * located using the {@link Springfactoriesloader} mechanism (keyed against this class). * Generally auto-configuration beans is {@link Conditional @Conditional} beans (most * often using {@link Conditionaloncl @ConditionalOnClass} and * {@link Conditionalonmissingbean @ConditionalOnMissingBean} annotations). * * @author Phillip Webb * @author Stephane Nicoll * @see Conditionalonbean * @see Conditionalonmissingbean * @see Condit Ionalonclass * @see Autoconfigureafter * @see springbootapplication * */@Target (Elementtype.type) @Retention ( Retentionpolicy.runtime) @Documented @inherited@autoconfigurationpackage@import ( Autoconfigurationimportselector.class) public @interface enableautoconfiguration {String Enabled_override_property =   "Spring.boot.enableautoconfiguration";    /** * Exclude Specific auto-configuration classes such that they would never be applied.   * @return The classes to exclude */class<?>[] Exclude () default {};    /** * Exclude specific auto-configuration class names such that they would never be * applied. * @return The class names to exclude * @since 1.3.0 */string[] Excludename () default {};}

The implementation is also injected into the Autoconfigurationimportselector class by a similar @import, and the class is loaded into the Spring boot container with a configuration class that modifies all of the conditional config annotations. Search all meta-inf/from classpath The spring.factories configuration file that instantiates the org.springframework.boot.autoconfigure.EnableAutoConfiguration corresponding configuration item as a callout by reflection The configuration and Javaconfig form of the IOC container Config class are then aggregated into one and loaded into the IOC container.

@ComponentScan

This note does not need to be introduced more, its role is automatically scanned to load the eligible bean.

Springapplication

The first thing that comes across from the project's entrance is the Springapplication class.

@SpringBootApplicationpublic class TutorialApplication {    public static void main(String[] args) {        SpringApplication.run(TutorialApplication.class, args);    }}

Enter the static method of the class run, you can see it in the construction of the Springapplication object

public static ConfigurableApplicationContext run(Class<?>[] primarySources,      String[] args) {   return new SpringApplication(primarySources).run(args);}

Entering the Springapplication construction method, you can see

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {   this.resourceLoader = resourceLoader;   Assert.notNull(primarySources, "PrimarySources must not be null");   this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));   this.webApplicationType = deduceWebApplicationType();   setInitializers((Collection) getSpringFactoriesInstances(         ApplicationContextInitializer.class));   setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));   this.mainApplicationClass = deduceMainApplicationClass();}

There are a few things that are done mainly:

    • Load source, here only application

    • Inferred Webapplicationtype, the enumeration has three types of none, SERVLET, reactive.

    • Set the initializer variable setinitializers, initialized with 6 initialization variables, these classes can be found in the spring.factories mentioned above

    • Set the listener, similar to the above Setinitializers implementation, resulting in the following 10 listeners

    • Finally infer the class with the main function, that is, the entry class, this is Tutorialapplication
private Class<?> deduceMainApplicationClass() {   try {      StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();      for (StackTraceElement stackTraceElement : stackTrace) {         if ("main".equals(stackTraceElement.getMethodName())) {            return Class.forName(stackTraceElement.getClassName());         }      }   }   catch (ClassNotFoundException ex) {      // Swallow and continue   }   return null;}
Run method

After watching how the Springapplication is initialized, let's look at what the Run method behind this is doing specifically.

Public Configurableapplicationcontext run (String ... args) {StopWatch StopWatch = new StopWatch ();   Stopwatch.start ();   Configurableapplicationcontext context = null;   collection<springbootexceptionreporter> exceptionreporters = new arraylist<> ();   Configureheadlessproperty ();   Springapplicationrunlisteners listeners = getrunlisteners (args);   Listeners.starting ();      try {applicationarguments applicationarguments = new defaultapplicationarguments (args);      Configurableenvironment environment = prepareenvironment (listeners, applicationarguments);      Configureignorebeaninfo (Environment);      Banner Printedbanner = printbanner (Environment);      context = CreateApplicationContext (); Exceptionreporters = Getspringfactoriesinstances (Springbootexceptionreporter.class, new Class[] {C      Onfigurableapplicationcontext.class}, context);        Preparecontext (context, environment, listeners, applicationarguments,    Printedbanner);      Refreshcontext (context);      AfterRefresh (context, applicationarguments);      Stopwatch.stop (); if (this.logstartupinfo) {new Startupinfologger (This.mainapplicationclass). logstarted (Getapplicati      OnLog (), stopWatch);      } listeners.started (context);   Callrunners (context, applicationarguments);      } catch (Throwable ex) {handlerunfailure (context, ex, exceptionreporters, listeners);   throw new IllegalStateException (ex);   } try {listeners.running (context);      } catch (Throwable ex) {handlerunfailure (context, ex, exceptionreporters, NULL);   throw new IllegalStateException (ex); } return context;}
    • StopWatch, this is a tool class in Spring-core that is used to run timings for a program (which is better than system.currenttimemillis for situations where it is often time consuming to calculate a method or interface)

    • Configureheadlessproperty configuration, set the system Properties Java.awt.headless, which is set to True, indicates that running on the server side, working in a mode without a monitor and mouse keyboard, simulates the input function.

    • Traverse listeners and start

    • Encapsulates a Appliationarguments object into the parameter args

    • Print Banner (the spring logo we see when we start)

    • The following is the initialization context and loading the context, the implementation will not go to look

If you feel that reading this article is helpful to you, please click " recommend " button, your " recommendation " will be my biggest writing motivation! If you want to keep an eye on my article, please scan the QR code, follow Jackiezheng's public number, I will push my article to you and share with you the high-quality articles I have read every day.

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.