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 is the automatic configuration mechanism in SpringBoot principle?

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

Share

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

This article shows you how the automatic configuration mechanism in the principle of SpringBoot is. The content is concise and easy to understand. It can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Preface

In the current java ecology, SpringBoot has become the de facto development standard, and most people are now programming for SpringBoot. SpringBoot is the further encapsulation of Spring, which integrates all kinds of class libraries and components needed by the upstream and downstream of the distributed system, and realizes out-of-the-box use, and the underlying basis of all this is the automatic configuration mechanism of SpringBoot.

Spring configuration class

Spring introduces configuration classes to: 1) replace tedious configuration files and 2) provide a more flexible way to define bean. Use the @ Configuration annotation to mark a configuration class and create a bean through the method that contains the @ Bean annotation, as shown in the following code

@ Configurationpublic class HelloAutoConfiguration {@ Bean HelloService helloService () {return new HelloService;}}

Is a simple configuration class and defines a bean for HelloService. On top of this, Spring also provides a conditional loading mechanism to dynamically control whether a configuration class is loaded or not. By implementing the org.springframework.context.annotation.Condition interface, developers can control the loading conditions of configuration classes and meet many complex scenarios.

SpringBoot automatic configuration

After introducing the configuration class of Spring, let's take a look at how SpringBoot uses this mechanism to implement automatic configuration.

The concept of automatic configuration

First, what is automatic configuration? Let's take a look at SpringBoot's definition of an autoconfiguration class:

Auto-configuration classes are regular Spring @ Configuration beans. They are located using the SpringFactoriesLoader mechanism (keyed against this class). Generally auto-configuration beans are @ Conditional beans (most often using @ ConditionalOnClass and @ ConditionalOnMissingBeanannotations).

The autoconfiguration class is a normal @ Configuration configuration class, usually with some @ Conditional condition annotations, and uses the SpringFactoriesLoader mechanism to locate and load them (not all, but there are other Spring-inherent loading methods, such as using @ ComponentScan package scanning or explicit @ Import to find them).

Operation mechanism of automatic configuration

Loading mode

The automatic configuration mechanism is controlled by the @ EnableAutoConfiguration annotation, so you need to enable this annotation on the entry class of the SpringBoot project, but usually we use @ SpringBootApplication instead, which is a collection of annotations that contains some necessary default configurations, including the @ EnableAutoConfiguration annotation, which is described in the annotation of its class:

Indicates a Configuration class that declares one or more @ Bean methods and also triggers auto-configuration and component scanning. This is a convenience annotation that is equivalent to declaring @ Configuration, @ EnableAutoConfiguration and @ ComponentScan.

It not only identifies a configuration class, but also enables automatic configuration and component scanning.

Going back to the @ EnableAutoConfiguration annotation, let's take a look at the definition of that annotation

@ Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Inherited@AutoConfigurationPackage@Import (AutoConfigurationImportSelector.class) public @ interface EnableAutoConfiguration {String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; Class [] exclude () default {}; String [] excludeName () default {};}

@ Import (AutoConfigurationImportSelector.class) is the key for the function to take effect. This annotation imports the AutoConfigurationImportSelector component into the Spring environment and enables the scanning and loading of the automatic configuration class, which implements the interface org.springframework.context.annotation.ImportSelector.

Public interface ImportSelector {/ * * Select and return the names of which class (es) should be imported based on * the {@ link AnnotationMetadata} of the importing @ {@ link Configuration} class. * @ return the class names, or an empty array if none * / String [] selectImports (AnnotationMetadata importingClassMetadata); Other omissions}

The selectImports method will be called when Spring starts, and is used to return all automatic configuration classes. The call entry is in the org.springframework.context.annotation.ConfigurationClassParser class, which is specially used to load and deal with all @ Configuration configuration classes. The specific loading details are not explained in this article because of the limited space. Readers can read the source code on their own. I may write another detailed explanation later. Let's move on to the selectImports method. Let's take a look at the loading process of the automatic configuration class. The specific implementation of this method by AutoConfigurationImportSelector is

@ Override public String [] selectImports (AnnotationMetadata annotationMetadata) {if (! isEnabled (annotationMetadata)) {return NO_IMPORTS;} AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry (annotationMetadata); return StringUtils.toStringArray (autoConfigurationEntry.getConfigurations ());}

The isEnabled method is a switch that controls whether automatic configuration is enabled. The logic is very simple, not to mention, looking down, the key logic is in the getAutoConfigurationEntry method, follow.

Protected AutoConfigurationEntry getAutoConfigurationEntry (AnnotationMetadata annotationMetadata) {if (! isEnabled (annotationMetadata)) {return EMPTY_ENTRY;} AnnotationAttributes attributes = getAttributes (annotationMetadata); List configurations = getCandidateConfigurations (annotationMetadata, attributes); configurations = removeDuplicates (configurations); Set exclusions = getExclusions (annotationMetadata, attributes); checkExcludedClasses (configurations, exclusions); configurations.removeAll (exclusions); configurations = getConfigurationClassFilter () .filter (configurations) FireAutoConfigurationImportEvents (configurations, exclusions); return new AutoConfigurationEntry (configurations, exclusions);}

It is easy to see that the loading logic is in the getCandidateConfigurations method, and the subsequent code is the process of de-duplication and filtering, and then read on.

Protected List getCandidateConfigurations (AnnotationMetadata metadata, AnnotationAttributes attributes) {List configurations = SpringFactoriesLoader.loadFactoryNames (getSpringFactoriesLoaderFactoryClass (), getBeanClassLoader ()); Assert.notEmpty (configurations, "No auto configuration classes found in META-INF/spring.factories. If you" + "are using a custom packaging, make sure that file is correct."); return configurations;}

This method is simple and obvious, just call SpringFactoriesLoader to load the corresponding content, and then we'll talk about the SpringFactoriesLoader mechanism.

SpringFactoriesLoader mechanism

SpringFactoriesLoader literally translates to factory loading mechanism, which is a set of class loading mechanism implemented by Spring following Java's SPI mechanism. The class is loaded by reading the META-INF/spring.factories file in the module, which is in Properties format, where the key part is a fully qualified name of Class, which can be an interface, abstract class, annotation, etc., while the value part is a list of implementation classes that support comma separation, such as

SpringFactoriesLoader is a utility class provided by Spring for reading and parsing META-INF/spring.factories files, and loads its corresponding implementation class list by passing in a Class type.

How to apply SpringFactoriesLoader in automatic configuration

After introducing SpringFactoriesLoader, let's take a look at how it is used in the autoconfiguration mechanism of SpringBoot. Back to the getCandidateConfigurations method above, let's take a look at this line.

List configurations = SpringFactoriesLoader.loadFactoryNames (getSpringFactoriesLoaderFactoryClass (), getBeanClassLoader ())

The first parameter is key corresponding to the Class type, and the second parameter is which ClassLoader to use to load the configuration file. Let's take a look at the specific Class returned by the getSpringFactoriesLoaderFactoryClass method.

Protected Class getSpringFactoriesLoaderFactoryClass () {return EnableAutoConfiguration.class;}

Very simply, directly return the class type corresponding to the @ EnableAutoConfiguration annotation, then the configuration of the automatic configuration class in the META-INF/spring.factories file is obvious, the first part of the screenshot above

# AutoConfigurationorg.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration,\ org.springframework.cloud.autoconfigure.LifecycleMvcEndpointAutoConfiguration,\ org.springframework.cloud.autoconfigure.RefreshAutoConfiguration,\ org.springframework.cloud.autoconfigure.RefreshEndpointAutoConfiguration,\ org.springframework.cloud.autoconfigure.WritableEnvironmentEndpointAutoConfiguration

Is the corresponding automatic configuration class. These classes configured here will be loaded into Spring as automatic configuration classes, and then processed accordingly to play the role of each class.

The above is what the autoconfiguration mechanism is in the principle of SpringBoot. Have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

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