This is the 19th day of my participation in the August More Text Challenge

Open the log

logging:
  level:
    org.springframework: trace
Copy the code

Starting the project you can see the main classes in turn in the log

PropertySourcesPropertyResolver

ClassPathBeanDefinitionScanner

DefaultListableBeanFactory

DockerApplication

SpringApplication

ConfigFileApplicationListener

ConfigServletWebServerApplicationContext

SpringFactoriesLoader

PathMatchingResourcePatternResolver

OnClassCondition

OnWebApplicationCondition

OnBeanCondition

ConfigurationClassBeanDefinitionReader

TomcatServletWebServerFactory

AutowiredAnnotationBeanPostProcessor

CommonAnnotationBeanPostProcessor

ThreadPoolTaskExecutor

RequestMappingHandlerMapping

TomcatWebServer

Its basic process

Load the configuration file, load the bean object, initialize the request mapper, and start the embedded Tomcat.

Configuration file loading logs

ConfigFileApplicationListener : Skipped missing config 'file:./config/application.properti ConfigFileApplicationListener : Skipped missing config 'file:./config/application.xml' (fi ConfigFileApplicationListener : Skipped missing config 'file:./config/application.yml' (fi ConfigFileApplicationListener : Skipped missing config 'file:./config/application.yaml' (f ConfigFileApplicationListener : Skipped missing config 'file:./application.properties' (fi ConfigFileApplicationListener : Skipped missing config 'file:./application.xml' (file:./ap ConfigFileApplicationListener : Skipped missing config 'file:./application.yml' (file:./ap ConfigFileApplicationListener : Skipped missing config 'file:./application.yaml' (file:./a ConfigFileApplicationListener : Skipped missing config classpath:/config/application.prope ConfigFileApplicationListener : Skipped missing config classpath:/config/application.xml ConfigFileApplicationListener : Skipped missing config classpath:/config/application.yml ConfigFileApplicationListener : Skipped missing config classpath:/config/application.yaml ConfigFileApplicationListener : Skipped missing config classpath:/application.properties ConfigFileApplicationListener : Skipped missing config classpath:/application.xml ConfigFileApplicationListener : Loaded config file 'file:... /target/classes/application.yml' (classpath:/application.yml) ConfigFileApplicationListener : Skipped missing config classpath:/application.yamlCopy the code

Log loading sequence

You can view the loading sequence of logs

  • file > classpath
  • Config > Current directory.
  • Properties > xml > ym l> yaml

The process of the run

The springApplication.run procedure builds the ApplicationContext

public ConfigurableApplicationContext run(String... args) {
  // Time statistics
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		ConfigurableApplicationContext context = null;
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
		configureHeadlessProperty();
    / / application to monitor
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting();
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
      // Load the environment variable configuration file
			ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
			configureIgnoreBeanInfo(environment);
			Banner printedBanner = printBanner(environment);
			context = createApplicationContext();
			exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);
      // Prepare the context
			prepareContext(context, environment, listeners, applicationArguments, printedBanner);
			// Refresh the context
      refreshContext(context);
			afterRefresh(context, applicationArguments);
			stopWatch.stop();
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
			}
      // The program is started
			listeners.started(context);
			callRunners(context, applicationArguments);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, listeners);
			throw new IllegalStateException(ex);
		}

		try {
      // The program is running
			listeners.running(context);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}
Copy the code

AnnotationConfigServletWebServerApplicationContext inheritance

AbstractApplicationContext (org.springframework.context.support)

|–GenericApplicationContext (org.springframework.context.support)

|–|–GenericWebApplicationContext (org.springframework.web.context.support)

|–|–|–ServletWebServerApplicationContext (org.springframework.boot.web.servlet.context)

|–|–|–|–AnnotationConfigServletWebServerApplicationContext (org.springframework.boot.web.servlet.context)

DefaultListableBeanFactory refreshBean used for loading the bean

public void refresh(a) 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 in 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(); }... }Copy the code

ApplicationListener and ApplicationEvent

ApplicationEvent partially inherits the relationship

ApplicationEvent (org.springframework.context)

|–SpringApplicationEvent (org.springframework.boot.context.event)

|–|–ApplicationEnvironmentPreparedEvent

|–|–ApplicationContextInitializedEvent (org.springframework.boot.context.event)

|–|–|–ApplicationEnvironmentPreparedEvent (org.springframework.boot.context.event)

|–|–|–ApplicationPreparedEvent (org.springframework.boot.context.event)

|–|–|–ApplicationStartedEvent (org.springframework.boot.context.event)

|–|–|–ApplicationReadyEvent (org.springframework.boot.context.event)

|–|–|–ApplicationFailedEvent (org.springframework.boot.context.event)

|–ApplicationContextEvent (org.springframework.context.event)

|–|–ContextClosedEvent (org.springframework.context.event)

|–|–ContextRefreshedEvent (org.springframework.context.event)

|–|–ContextStoppedEvent (org.springframework.context.event)

|–|–ContextStartedEvent (org.springframework.context.event)

|– …

SimpleApplicationEventMulticaster used to manage ApplicationListener and ApplicationEvent, it’s a bit like Java swing of event processing, such as the mouse to click send an event, Then a listener handles the event.

MulticastEvent is used to trigger listener and Envent events, which eventually call the Listener’s onApplicationEvent method. Such as ConfigFileApplicationListener ApplicationEnvironmentPreparedEvent event processing. LoggingApplicationListener ApplicationEnvironmentPreparedEvent event processing.

The listener starts. ==> The listener finishes. ==> The listener is running

listeners.starting(); . listeners.started(context); . listeners.running(context);Copy the code

Listeners keeps a list of registered SpringApplicationRunListener, the processing of listeners that call each listener processing cycle.

EventPublishingRunListener SpringApplicationRunListener implementation class.

The Listener by SimpleApplicationEventMulticaster# multicastEvent broadcast events, doInvokeListener call event handling, The listener calls onApplicationEvent to handle the event.

Listeners. Started (context) of events is spread through AbstractApplicationContext# publishEvent earlier Event processing and correlation of events, Through SimpleApplicationEventMulticaster broadcast events, events at the same time to the spread of the parent class.

Take a look at the listening for the entire startup process

public interface SpringApplicationRunListener {

 * Called immediately when the run method has first started. Can be used for very early initialization. */
 default void starting(a) {}* Called once the environment has been prepared, but before the * {@link ApplicationContext} has been created.
  * @param environment the environment
  */
 default void environmentPrepared(ConfigurableEnvironment environment) {}/** * context ready to complete * Called once the {@link ApplicationContext} has been created and prepared, but
  * before sources have been loaded.
  * @param context the application context
  */
 default void contextPrepared(ConfigurableApplicationContext context) {}* Called once the application context has been loaded but before it has been * refreshed. *@param context the application context
  */
 default void contextLoaded(ConfigurableApplicationContext context) {}Checksum * The context has been refreshed and The application has started but * {@link CommandLineRunner CommandLineRunners} and {@link ApplicationRunner
  * ApplicationRunners} have not been called.
  * @param context the application context.
  * @since2.0.0 * /
 default void started(ConfigurableApplicationContext context) {}And ** * is running * Called immediately before the run method. when the application context has * been refreshed and all {@link CommandLineRunner CommandLineRunners} and
  * {@link ApplicationRunner ApplicationRunners} have been called.
  * @param context the application context.
  * @since2.0.0 * /
 default void running(ConfigurableApplicationContext context) {}/** * failed * Called when a failure occurs when running the application. *@param context the application context or {@code null} if a failure occurred before
  * the context was created
  * @param exception the failure
  * @since2.0.0 * /
 default void failed(ConfigurableApplicationContext context, Throwable exception) {}}Copy the code

conclusion

The SpirngApplication handles some of the startup events through a listener at startup time. Context loading process first obtains the environment variable configuration file, creates the initial context, prepareContext phase binds context, environment and listener, processes subsequent events, In the refreshContext stage, beans are loaded and postProcessors are processed, automatic assembly is loaded, conditional configuration bean is loaded, and finally the context ApplicationContext of the assembled bean is generated. Finally, the publishing program is started and running. And a listener to process, so that the program is started.

Today, I will write about this for the time being.