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

What are the preparations for Spring application context in SpringBoot

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

Share

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

What is the preparation of Spring application context in SpringBoot? for this question, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

Preparation of Spring application context

First, take a look at the core functions and processes of prepareContext as a whole through figure 4-4.

With the flow chart, take a look at the source code and functional notes of the prepareContext method in SpringApplication.

Private void prepareContext (ConfigurableApplicationContext context,ConfigurableEnvironment environment, SpringApplicationRunL isteners listeners, Applicat ionArguments applicat ionArguments, Banner printedBanner) {/ / configuration environment context without context. SetEnvironment (environment); / / Application context post-processing postProcessApplicationContext (context); / / before context refresh, ApplicationContext Initializer initializes context applyInitializers (context); / / notifies listeners that context is ready. This method takes the above as context preparation phase, and the following is context loading phase. ContextPrepared (context); / / print the log and start Profile if (this. LogStartupInfo)-logStartupInfo (context. GetParent () = = nu1l); logStartupProfileInfo (context);} / / get ConfigurableL istableBeanFactory and register singleton object ConfigurableL istableBeanFactory beanFactory = context. GetBeanFactory (); beanFactory. RegisterSingleton ("springApplicat ionArguments", applicationAr guments); if (printedBanner! = null) {/ / register the print log object beanF actory. RegisterSingleton ("springBootBanner", printedBanner); if (beanFactory instanceof DefaultlistableBeanFactory) {/ / does not allow you to overwrite ((DefaultListableBeanFactory) beanFactory). SetAllowBeanDefinitionOverriding (this. AllowBeanDefinitionOverriding); / / get all configuration sources, including primarySources and sources Set sources = getAllSources (); Assert. NotEmpty (sources, "Sources must not be empty"); / / load Bean from sources into context load (context, sources. ToArray (new 0bject [0])); / / the hidden listener context has finished loading listeners. ContextLoaded (context);}

From the flow chart and specific code, we can see that two steps are completed in this method: the preparation and loading of the application context.

Next, we will explain in detail the specific source code.

Application context preparation phase

In the context preparation phase, there are three main steps: setting environment on context, applying context post-processing and ApplicationContextlnitializer initializing context operation.

The first is to set up environment for context, the code and business operation are very simple.

Public void setEnvironment (ConfigurableEnvironment environment) {/ / sets the environment super of context. SetEnvi ronment (environment); / / sets the conditionEvaluator property this.reade er of the reader property of context. SettEnvironment (environment); / / sets the environment property this of the scanner property of context. Scanner. SetEnvi ronment (envi ronment);}

Then, the post-processing above and below should be used in the Spring, which is done through the postProcessApplicationContext method.

Protected void postProcessApplicat ionContext (ConfigurableApplicat ionConEext context) {f (this. BeanNameGenerator! = null) {/ / if beanNameGenerator is null, register the current beanNameGenerator in the line with the default name context. GetBeanFactory (). Regi sterSingleton (Annotat ionConfigUtils. Conf IGURATION BEAN NAME GENERATOR, this. BeanNameGenerator); if esourceLoader is null, set if (this. ResourceLoader! = null) {F (context instanceof GenericApplicationContext) {((GenericApplicationContext) context) according to the type of context. SetResourcel oader (this. Resource Loader); if (context instanceof DefaultResourceLoader) {((DefaultResourceLoader) context). SetClassLoader (this.resourceLoader. GetClassLoader (); / / if true, get the conversion service f (this. AddConversionService) {context. GetBeanFactory (). SetConversionService (ApplicationConversionService. GetSharedInstance ();}

The main purpose of the postProcessApplicationContext method is to complete the post operation of the above and the following, which includes the settings of beanNameGeneratorResourceL oader.ClassL oader and ConversionService by default. This method can be implemented by subclass overrides to add more operations.

At this stage, beanNameGenerator and resourceL oader are both null, so only the last-first step of the setup transformation service is performed.

Finally, the context is initialized through the applylnitializers method before notifying the listener that context is ready to complete.

The ApplicationContextInitializer we used is the same value we set in the itializers variable during the SpringApplication initialization phase, but it is de-duplicated and sorted when it is obtained through the getlnitializers method.

Protected void applyInitializers (ConfigurableApplicat ionContext context) {/ gets the ApplicationContextInitializer collection and traverses the for (ApplicationContextInitializer initializer: getInitializers ()) {/ / parses the current initial izer. The generic parameter Class requiredType = GenericTypeResolver of the implemented Appl icat ionContextInitializer. ResolveTypeArgument (initializer. GetClass (), ApplicationContextInitializer.class); 1 assert to determine whether the required analogy matches the context type Assert. IsInstanceOf (requiredType, context, "Unable to call initializer."); / / initialize context initializer. Initialize (context);}}

After the above operation is completed, the program calls the contextPrepared method of SpringApplicationRunListeners to notify the listener, and the first phase of the preparation operation is complete.

Application context loading phase

The application context loading phase includes the following steps: printing the settings of the log and Profile, setting whether the registration is allowed to be overwritten, obtaining all configuration sources, loading the configuration sources into the context, and informing the monitor that contex loading is complete.

The first operation to enter the application context loading phase is to print the log and Profile settings, which will not be explained. Then, you get the ConfigurableL istableBeanFactory and register the singleton object, which contains:

ApplicationArguments and Banner. When BeanFactory is DefaultL istableBeanFactory, enter the processing logic that sets whether or not to override registration.

It is important to note that when the singleton object of the ApplicationArguments class is registered, it means that we can use the object through dependency injection when using the Spring application context.

@ Resource private ApplicationArguments applicat ionArguments

Complete with. After the operation, we enter the processing stage of the configuration source information, and this step uses the getAllSources method to merge the configuration source information.

Public Set getAllSources () {Set allSources = new LinkedHashSet (); if (! CollectionUtils.isEmpty (this. PrimarySources) {allSources.addAll (this.primarySources); if (! CollectionUtils. IsEmpty (this. Sources) {allSources. AddAll (this.sources);}}

Return Collections. UnmodifiableSet (allSources);} the above operation logic is very simple. If there is no primarySources configuration source or sources configuration source in the Set collection, add it to the Set, set the Set to be unmodifiable, and return.

As mentioned in the previous section, the value of the variable primarySources comes from the construction parameter of SpringApplication, and the value of the variable sources comes from the setResources method.

After all the configuration source information is obtained, the configuration source information is loaded into the context through the load method, as shown in the following code.

Protected void load (ApplicationContext context, Object [] sources) {/ Log printing BeanDefinitionLoader loader = createBeanDefinitionLoader (getBeanDefinitionRegistry (context), sources); f (this. BeanNameGenerator! = nu1l). Loader. SetBeanNameGenerator (this. BeanNameGenerator); if (this.resourceLoader! = nu1l) {loader. SetResourceLoader (this. ResourceLoader), if (this. Environment! = null) {loader. SetEnvironment (this. Environment); loader. Load ();}

This method mainly completes the loading operation of configuration resources through BeanDefinitionL oader. If we take a closer look at the source code of the method createBeanDefinitionL oader, we will see that it finally calls the constructor of BeanDefinitionL oader and initializes it.

BeanDefinitionLoader (BeanDefinitionRegistry registry, Object... Sources) {this. Sources = sources; this. AnnotatedReader = new AnnotatedBeanDefinitionReader (registry); this. XmlReader = new XmlBeanDefinitionReader (registry); if (isGroovyPresent ()) this. GroovyReader = new GroovyBeanDefinitionReader (registry);}

Through the construction method of BeanDefinitionLoader, we can see that BeanDefinitionLoader supports many types of load operations based on AnnotatedBeanDefinitionReaderXmlBeanDefinitionReader, GroovyBeanDefinitionReader, and so on.

After executing the creation and basic property settings of the BeanDefinitionL oader, call its load method, which finally executes the following code.

Private int load (0bject source) {Assert. NotNull (source, "Source must not be null"); if (source instanceof Class) {return load ((Class) source);} if (source instanceof Resource) return load ((Resource) source);} if (source instanceof Package) {return load ((Package) source);} if (source instanceof CharSequence) {return load ((CharSequence) source); throw new IllegalArgumentException ("Invalid source type" + source. GetC lass ();}

As you can see from the above code, the scope of BeanDefinitionLoader loading support includes:

There are four kinds of Class, Resource, Package and CharSequence. We mentioned earlier that the sources of the variable sources are the primarySources configuration source and the sources configuration source. The variable primarySources receives a type of Class at initialization, while the variable sources receives a parameter of the String collection through the set (Set) method.

Therefore, in the process of practical use, the judgment branch of Resource and Package can never enter the execution stage.

After completing the above operation, the contextL oaded method of SpringApplicationRunListeners is then executed to inform the listener that the context loading is complete, and the preparation phase of the entire Spring application context is complete.

This is the answer to the question about the preparation of Spring application context in SpringBoot. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

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

Development

Wechat

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

12
Report