Writing in the front

In these days of Coding, I always started to learn after encountering problems. After solving the problems, I would release the knowledge with compassion. In addition to some business problems, I left less knowledge. Always want to read the source code, but are nothing. Sum up in addition to too much business, their lazy, but also because is not to find a good way to learn.

First of all, I am impetuous and like to get immediate results. So in the previous reading, always found that read a lot, what also did not precipitate, on the exasperation, but the source code reading (knowledge learning) is never an overnight thing. Seeking quick success will only lead to disastrous results.

Secondly, I give priority to the depth of my study, so I will go deep in one point. I find it is still in the first few lines after reading for half a day, and I feel that I have made little progress in the whole day. But the reading of the source code can not be so, only with a global awareness, in order to better understand the local. Build context –> Rich details!

Finally, this article only as their own source code learning a record, if there is a wrong please don’t hesitate to correct! Thank you

SpringBoot

What is SpringBoot?

**Build Anything with Spring Boot: **Spring Boot is the starting point for building all Spring-based applications. Spring Boot is designed to get you up and running as quickly as possible, with minimal upfront configuration of Spring.

SpringBoot is the starting point for Spring applications. It is more of a design concept and rules and standards. It encapsulates a lot of things, and we can use all kinds of starter, and we can use it out of the box.

What are the benefits of SpringBoot?

  1. Simplifies the development of Spring applications;
  2. With a large number of default configurations, the mainstream framework can be integrated without configuration, reducing the tedious process of SSM construction
    • web.xml
    • Database configuration XML, configure log files
    • .

How do I start a SpringBoot application?

// This annotation identifies this class as the project's startup class. The main method in this class is executed when the JAR package is finished
@SpringBootApplication
public class WorkToolsApplication {

    public static void main(String[] args) {
      	// The springApplication.run method is the entry to the programSpringApplication.run(WorkToolsApplication.class, args); }}Copy the code

@springBootApplication: Mark this class is the project’s startup class. You just need to execute the main method in the class of this annotation tag to start the class;

Springapplication.run () : The run method is a static method that returns a SpringApplicationContext.

Run method

Static helper, which can run a SpringApplication from a specified source with default Settings
public static ConfigurableApplicationContext run(Class
        primarySource, String... args) {
		return run(newClass<? >[] { primarySource }, args); }// The final method of the above method call
public static ConfigurableApplicationContext run(Class
       [] primarySources, String[] args) {
		return new SpringApplication(primarySources).run(args);
}
Copy the code

Based on the code above, we can see that the run method does only two things:

  1. New a SpringApplication object;
  2. Executes the Run method of the SpringApplication object, returning a configurable application context (or a Spring application);

Build a Spring application (New SpringApplication())

/ / primarySources for incoming WorkToolsApplication. Class
public SpringApplication(Class
       ... primarySources) {
		this(null, primarySources);
}

// The constructor of the call
public SpringApplication(ResourceLoader resourceLoader, Class
       ... primarySources) {
  		// According to the method called, resourceLoader is NULL
		this.resourceLoader = resourceLoader;
 		/ / check whether incoming primarySources is empty, this is a WorkToolsApplication. Class
		Assert.notNull(primarySources, "PrimarySources must not be null");
    		// Put the incoming class into a member variable of the SpringApplication
		this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
   		 // Get the type of the application and assign it to the member variable. Obtaining methods will be explained later
		this.webApplicationType = WebApplicationType.deduceFromClasspath();
    		// Initialize the boot program
		this.bootstrappers = new ArrayList<>(getSpringFactoriesInstances(Bootstrapper.class));
    		// Set the initializer
		setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
    		// Set the listener
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
   		 // Infer and set the class of the main application
		this.mainApplicationClass = deduceMainApplicationClass();
}
Copy the code

The run method of the SpringApplication

/**
	 * Run the Spring application, creating and refreshing a new
	 * {@link ApplicationContext}.
	 * @param args the application arguments (usually passed from a Java main method)
	 * @return a running {@link ApplicationContext}
	 */
// Run a Spring application to create and refresh a new ApplicationContext
public ConfigurableApplicationContext run(String... args) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
    		// Create a bootstrap context
		DefaultBootstrapContext bootstrapContext = createBootstrapContext();
		ConfigurableApplicationContext context = null;
    		// Set the headless property
		configureHeadlessProperty();
    		// Get running listeners
		SpringApplicationRunListeners listeners = getRunListeners(args);
  			// I don't understand
		listeners.starting(bootstrapContext, this.mainApplicationClass);
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
      			// Create a configurable environment
			ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
      			// Configure the ignorable bean information in the environment information
			configureIgnoreBeanInfo(environment);
      			// Banner print
			Banner printedBanner = printBanner(environment);
      			// Create an application context
			context = createApplicationContext();
      			// TODO
			context.setApplicationStartup(this.applicationStartup);
      			// Prepare the context
			prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
			// Refresh the application context, that is, call the refresh method of the corresponding program context
      			refreshContext(context);
      			// The operation after the context is refreshed
			afterRefresh(context, applicationArguments);
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
			}
			listeners.started(context);
      			// Find all runners (implementing ApplicationRunner, CommandLineRunner) and execute the corresponding run method.
			callRunners(context, applicationArguments);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, listeners);
			throw new IllegalStateException(ex);
		}

		try {
      			// All listeners runing up, setting their context
			listeners.running(context);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, null);
			throw new IllegalStateException(ex);
		}
  		// Return context
		return context;
	}
Copy the code

Among them, the most important are:

  1. CreateBootstrapContext creates the boot context;
  2. GetRunListeners get listeners;
  3. PrepareEnvironment Prepares environment information.
  4. CreateApplicationContext creates the application context;
  5. PrepareContext Prepares the context;
  6. RefreshContext refreshContext;
  7. CallRunners call runner’s methods;

conclusion

This article is the first chapter of the introduction. Through reading this article, we can understand the general steps of the previous SpringApplication.

  1. Mark a class with the @SpringBootApplication annotation with the main method as the key to start the program.
  2. The main method uses SpringApplication.run () to initialize a Spring application and set its context;
    1. New a SpringApplication object;
      1. Set resourceLoader;
      2. Set the main resource class, that is, the class of the incoming entry class.
      3. Set the application type.
      4. Set up the boot;
      5. Initialize and set the initializer;
      6. Gets and sets the listener instance;
      7. Set the main application class.
    2. Execute the run method of this object;
      1. Create a context for the boot;
      2. Configure headless attributes (temporarily not important)
      3. Get running listeners;
      4. Create an applicationArguments object using args;
      5. Use listeners, bootstrap contexts, and applicationArguments to create a configurable environment object.
      6. Configure ignorable bean information in the environment object.
      7. Create an application context (the context to return eventually);
      8. Prepare this context, using bootcontext, environment objects, listeners, application parameters, and so on;
      9. Refresh context;
      10. Callback to user-configured Runners;
      11. Let’s make the listener run as context;
      12. Return this context;
  3. Initialize and run a SpringBoot container;

Information to learn

SpringBoot source code analysis (a) —– SpringBoot core principle introduction

SpringBoot source code analysis (two) —– SpringBoot essence: start process source analysis