Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Initialization of SpringApplication instance in springboot2.0.6

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "SpringApplication instance initialization in springboot2.0.6". In daily operation, I believe many people have doubts about SpringApplication instance initialization in springboot2.0.6. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "SpringApplication instance initialization in springboot2.0.6". Next, please follow the editor to study!

SpringApplication instance initializes public SpringApplication (ResourceLoader resourceLoader, Class...) PrimarySources) {/ / set the resource loader property this.resourceLoader = resourceLoader; / / verify that the main loaded resource cannot be empty, and an exception Assert.notNull (primarySources, "PrimarySources must not be null") is thrown for null / / set the primarySources (main source) attribute [which will be handed to BeanDefinitionLoader later to load these primarySources into the scanner (scanner) to avoid repeatedly scanning these classes into the container] this.primarySources = new LinkedHashSet (Arrays.asList (primarySources)); / / get the ApplicationContext type and set it to the webApplicationType property this.webApplicationType = WebApplicationType.deduceFromClasspath () / / get the application context initializer instance collection and set it to setInitializers ((Collection) getSpringFactoriesInstances (ApplicationContextInitializer.class)) in the initializers property; / / get the application listener instance collection and set it to the setListeners ((Collection) getSpringFactoriesInstances (ApplicationListener.class)) in the listeners property / / find the main (main entry application class) class, here is the CoreServerApplication class this.mainApplicationClass = deduceMainApplicationClass ();} 1. WebApplicationType is an enumeration class that is used to determine what type of current springboot project is.

NONE: it is not an application running under a web container and a built-in web service should not be started.

SERVLET: is required to run in a servlet-based web application and needs to start a built-in servlet-web service.

REACTIVE: still running in reactive's web application and needs to start a reactive-web service.

2. WebApplicationType.deduceFromClasspath () get the ApplicationContext type private static final String [] SERVLET_INDICATOR_CLASSES = {"javax.servlet.Servlet", "org.springframework.web.context.ConfigurableWebApplicationContext"}; private static final String WEBMVC_INDICATOR_CLASS = "org.springframework." + "web.servlet.DispatcherServlet"; private static final String WEBFLUX_INDICATOR_CLASS = "org." + "springframework.web.reactive.DispatcherHandler"; private static final String JERSEY_INDICATOR_CLASS = "org.glassfish.jersey.servlet.ServletContainer" Private static final String SERVLET_APPLICATION_CONTEXT_CLASS = "org.springframework.web.context.WebApplicationContext"; private static final String REACTIVE_APPLICATION_CONTEXT_CLASS = "org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext"; static WebApplicationType deduceFromClasspath () {if (ClassUtils.isPresent (WEBFLUX_INDICATOR_CLASS, null) & &! ClassUtils.isPresent (WEBMVC_INDICATOR_CLASS, null) & &! ClassUtils.isPresent (JERSEY_INDICATOR_CLASS, null)) {return WebApplicationType.REACTIVE } for (String className: SERVLET_INDICATOR_CLASSES) {if (! ClassUtils.isPresent (className, null)) {return WebApplicationType.NONE;}} return WebApplicationType.SERVLET;}

According to org.springframework.util.ClassUtils 's static method isPresent, determine whether classpath contains WEBFLUX_INDICATOR_CLASS and does not contain WEBMVC_INDICATOR_CLASS and JERSEY_INDICATOR_CLASSERVLET_INDICATOR_CLASSE. If the condition is met, it means to start a WEB application of REACTIVE type. If the above conditions are not met and there are classes contained in SERVLET_INDICATOR_CLASSES, it means to start a WEB application of SERVLET type, otherwise start a standard application.

Whether or not to launch a WEB application depends on whether there are javax.servlet.Servlet and org.springframework.web.context.ConfigurableWebApplicationContext or org under classpath. Springframework.web.reactive.DispatcherHandler and no org.springframework.web.servlet.DispatcherServlet and org.glassfish.jersey.servlet.ServletContainer.

3. SetInitalizers ()

Initialize all available ApplicationContextInitializer under classpath

The ApplicationContextInitializer application initializer, which does some initialization work, is called before springboot prepares to call the prepareContext method to prepare the spring container (at this time the spring container has been created and requires refresh) to perform some operations at this point in time: such as setting servletContext, etc.

By default, the getSpringFActoriesInstances method finds the collection of permission names for which key is of type ApplicationContextInitializer from the spring.factories file:

Org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer:

Register the post processor (ConfigurationWarningsPostProcessor) in the application context

Org.springframework.boot.context.ContextIdApplicationContextInitializer

Set the application context ID and register the ContextId (ContextIdApplicationContextInitializer) object generated above with the current application context as a singleton bean.

Org.springframework.boot.context.config.DelegatingApplicationContextInitializer

Execute the initializers specified in the environment property "context.initializer.classes", and then execute these initializers. Here, the ApplicationContextInitializer implemented by the springboot application itself does some initialization of the application.

Org.springframework.boot.context.web.ServerPortInfoApplicationContextInitializer

Register yourself as a listener in the application context

Org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer

Register the post processor (CachingMetadataReaderFactoryPostProcessor) in the application context

Org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener

Registering listeners with the application context (ConditionEvaluationReportListener) sets the "report" property when the application context implements GenercApplicationContext

(figure 1-2 applicationContextInitializer related in spring.factories file in spring-boot.jar)

(figure 1 executes getSpringFactoriesInstances (ApplicationContextInitializer.class) to get the applicationContextInitializer-related factory classes in the spring.factories file and initialize them.

(figure 2 instances property value in the springApplication object)

4. SetListeners ()

Initialize all available ApplicationListener under classpath

ApplicationListener Application event (ApplicationEvent) listener

The application events (ApplicationEvent) here include application startup events (ApplicationStartedEvent), failure events (ApplicationFailedEvent), preparation events (ApplicationPreparedEvent), etc.

The application event listener is bound to the listening event. For example, ConfigServerBootstrapApplicationListener binds only to ApplicationEnvironmentPreparedEvent events, LiquibaseServiceLocatorApplicationListener binds only to ApplicationStartedEvent events, LoggingApplicationListener binds to all events, etc.

By default, the getSpringFactoriesInstances method finds out that the key is of type ApplicationListener from the spring.factories file, and the collection of fully qualified names of the class is:

Org.springframework.boot.autoconfigure.BackgroundPreinitializer

Org.springframework.boot.ClearCachesApplicationListener

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.context.logging.ClasspathLoggingApplicationListener

Org.springframework.boot.context.logging.LoggingApplicationListener

Org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

(figure 3-1 applicationlistener related in spring.factories file in spring-boot.jar)

(figure 3-2 applicationlistener related in spring.factories file in spring-boot.jar)

(figure 4 executes getSpringFactoriesInstances (Applicationlistener.class) to get the applicationContextInitializer-related factory classes in the spring.factories file and initialize them.)

Because spring has a lot of events such as ContextRefreshedEvent,ContextStartedEvent and so on, we have an ApplicationListener to listen to these events and deal with them accordingly.

In fact, applicationContext calls its publishEvent to send some event, this method will find a lot of listener interested in the event to call its onApplicationEvent, and these are implemented by SimpleApplicationEventMulticaster, if there is an Executor, it will give priority to using Executor to execute, which may cause our callback to be asynchronous.

ApplicationContext also propagates event to its parent container (we know that AnnotationConfigApplicationContext already has a lot of parent containers)

Another strategy here is to add the event to the earlyApplicationEvents if the earlyApplicationEvents exists, send it later, and send it directly if it doesn't exist.

Applicationevent contains timestamps, springboot startup classes (source), and our spring container

5. Customize ApplicationContextInitializer and ApplicationListener

If we want to write our own implementation classes for ApplicationContextInitializer and ApplicationListener in our code, we can do the following:

Create a META-INF/spring.factories file in the project that stores our implementation classes in key=value

You can also manually call the corresponding add method of SpringApplication

Configure context.initializer.classes = implementation class in our application.properties (get our configured initializer through DelegatingApplicationContextInitializer, which can be called during prepareContext), and context.listener.classes = implementation class (cannot listen for some events when springboot starts, because the implementation class has not been added to the container at that time)

Although we use @ Configuration to say that our ApplicationListener implementation class is added to the spring container, and can also listen to some events that the program is running normally (unable to listen to some events during springboot startup, because the implementation class has not yet joined the container at that time), if we want to listen for all events, we'd better configure them in the above three ways so that we can listen when springboot starts.

6. GetSpringFactoriesInstances ()

Get the fully qualified name of the corresponding class according to the propties file in the specified directory by loading the class in the system

Summary

The main construction method of SpringApplication is to set Initializers and Listeners and set primaryClass at the same time to facilitate loading primaryClass first, and also determine the current running environment of springboot by the way.

At this point, the study on "initialization of SpringApplication instances in springboot2.0.6" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report