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 principle of SpringBoot automatic assembly in Java?

2025-03-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

In this article, the editor introduces in detail "what is the principle of SpringBoot automatic assembly in Java", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "what is the principle of SpringBoot automatic assembly in Java" can help you solve your doubts.

Operation principle

In order to study, we normally start with the pom.xml of the parent project.

Pom.xml

The parent dependency spring-boot-starter-parent is mainly used to manage the project's resource filtering and plug-ins

Org.springframework.boot spring-boot-starter-parent 2.2.5.RELEASE

Click on the parent to check it out and find that there is another parent that depends on spring-boot-dependencies. The parent dependency here is the place to really manage all the dependent versions in the springboot application, and it is the version control center of springboot.

Org.springframework.boot spring-boot-dependencies 2.2.5.RELEASE.. /.. / spring-boot-dependencies

Initiator: scene initiator for spring-boot-starter-xxx:springboot

Spring-boot-starter-web: import components that web depends on

Org.springframework.boot spring-boot-starter-web main program

@ SpringBootApplication

Function: Mark that this is a springboot main program class, indicating that this is a springboot application, and springboot is a springboot application started by running the mian method of this class.

@ SpringBootApplication / / Mark that this is a main program class, indicating that this is a springboot application public class Springboot01HelloworldApplication {public static void main (String [] args) {/ / where a service is started rather than a method executed. SpringApplication.run (Springboot01HelloworldApplication.class, args);}}

Click @ SpringBootApplication to continue your research, and you will find three annotations of @ SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan.

SpringBootConfiguration@EnableAutoConfiguration@ComponentScan (excludeFilters = {@ Filter (type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class}), @ Filter (type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class})})

1.@ComponentScan: spring automatic scan package

This, which we saw in the spring configuration file, is used to automatically scan and load eligible components or bean, and load bean into the IOC container.

2.@SpringBootConfiguration: configuration class for springboot

Tagging on a class indicates that the class is the configuration class for springboot, and here it means that the SpringBootApplication class is the configuration class for springboot.

If we continue to click @ SpringBootConfiguration to check it out, we will find the annotation @ Configuration.

2.1 @ Configuration: configuration class, which is used to configure the xml file for spring

If we continue to click @ Configuration to check it out, we will find the annotation @ Component.

2.2 @ Component: component, indicating that the startup class itself is also a component, which is responsible for launching the application.

At this point, we have finished studying the @ SpringBootConfiguration line.

3.@EnableAutoConfiguration: turn on auto-assembly and use @ EnableAutoConfiguration to help us automatically configure what we need to configure before.

If we continue to click @ EnableAutoConfiguration to check it out, we will find @ AutoConfigurationPackage and @ Import ({AutoConfigurationImportSelector.class}).

@ 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 {};}

3. 1 @ AutoConfigurationPackage Auto Assembly package

Continue to click in to check, and the annotation @ Import ({Registrar.class}) appears

3.1.1 @ Import ({Registrar.class}): spring underlying note to import a component into the container

Registrar.class: scan all components in the package where the main startup class is located and all the subpackages under the package to the Spring container.

At this point, we have finished studying the @ AutoConfigurationPackage line.

3.2 @ Import ({AutoConfigurationImportSelector.class}): import components to the container

AutoConfigurationImportSelector.class: automatically assembles the import selector.

Imported selector analysis:

1. Let's click on the source code of the class AutoConfigurationImportSelector.class to explore.

two。 Let's click getCandidateConfigurations for further analysis.

Protected List getCandidateConfigurations (AnnotationMetadata metadata, AnnotationAttributes attributes) {List configurations = SpringFactoriesLoader.loadFactoryNames (this.getSpringFactoriesLoaderFactoryClass (), this.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;}

2.1Use the getSpringFactoriesLoaderFactoryClass () method to return the annotated class EnableAutoConfiguration.class that we saw at the beginning to start the automatic configuration file

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

2.2 finding that it calls the static method of the SpringFactoriesLoader class, we click loadFactoryNames to enter loadFactoryNames ()

Public static List loadFactoryNames (Class factoryType, @ Nullable ClassLoader classLoader) {ClassLoader classLoaderToUse = classLoader; if (classLoader = = null) {classLoaderToUse = SpringFactoriesLoader.class.getClassLoader ();} String factoryTypeName = factoryType.getName (); return (List) loadSpringFactories (classLoaderToUse) .getOrDefault (factoryTypeName, Collections.emptyList ());}

Find that it calls the loadSpringFactories () method again and click in to check it.

Private static Map loadSpringFactories (ClassLoader classLoader) {Map result = (Map) cache.get (classLoader); if (result! = null) {return result;} else {HashMap result = new HashMap (); try {Enumeration urls = classLoader.getResources ("META-INF/spring.factories"); while (urls.hasMoreElements ()) {URL url = (URL) urls.nextElement (); UrlResource resource = new UrlResource (url) Properties properties = PropertiesLoaderUtils.loadProperties (resource); Iterator var6 = properties.entrySet (). Iterator (); while (var6.hasNext ()) {Entry entry = (Entry) var6.next (); String factoryTypeName = ((String) entry.getKey ()). Trim (); String [] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray ((String) entry.getValue ()); String [] var10 = factoryImplementationNames Int var11 = factoryImplementationNames.length; for (int var12 = 0; var12

< var11; ++var12) { String factoryImplementationName = var10[var12]; ((List)result.computeIfAbsent(factoryTypeName, (key) ->

{return new ArrayList ()) .add (factoryImplementationName.trim ());} result.replaceAll ((factoryType, implementations)-> {return (List) implementations.stream (). Distinct (). Collect (Collectors.collectingAndThen (Collectors.toList (), Collections::unmodifiableList)); cache.put (classLoader, result) Return result;} catch (IOException var14) {throw new IllegalArgumentException ("Unable to load factories from location [META-INF/spring.factories]", var14);}

Source code analysis:

MultiValueMap result = (MultiValueMap) cache.get (classLoader); get classLoader, and we return and see that what we get here is the class itself annotated by EnableAutoConfiguration

Enumeration urls = classLoader! = null? ClassLoader.getResources ("META-INF/spring.factories"): ClassLoader.getSystemResources ("META-INF/spring.factories"); get a resource "META-INF/spring.factories"

While loop, which traverses the read resources and encapsulates them into a Properties

Spring.factories file

Let's find any one of the autoconfiguration classes above to open it, for example: WebMvcAutoConfiguration

They are all familiar configurations, so the real implementation of automatic configuration is to search all META-INF/spring.factories configuration files from classpath and put the corresponding org.springframework.boot.autoconfigure. The configuration items under the package are instantiated into JavaConfig container configuration classes in the form of JavaConfig labeled @ Configuration through reflection, and then these are summarized into an instance and loaded into the IOC container.

Summary

SpringBoot gets the value specified by EnableAutoConfiguration from the META-INF/spring.factories under the classpath when starting

Import these values into the container as automatic configuration classes, and the automatic configuration classes will take effect and help us with automatic configuration.

The overall solution and automatic configuration of the entire J2EE are in the jar package of springboot-autoconfigure.

It imports a lot of xxxAutoConfiguration classes into the container, that is, to import all the components needed for the scene into the container and configure these components.

With the automatic configuration class, we do not have to write the configuration injection function components manually.

Main startup class

SpringApplication

@ SpringBootApplicationpublic class SpringbootApplication {public static void main (String [] args) {SpringApplication.run (SpringbootApplication.class, args);}}

Analysis:

SpringbootApplication.class: the entrance to the application parameter

Args: command line argument

This method returns a ConfigurableApplicationContext object

The main things SpringApplication does:

Infer whether the type of application is an ordinary project or a Web project

Find and load all available initializers and set them to the initializers property

Find all the application listeners and set them to the listeners property

Infer and set the definition class of the main method to find the main class that runs

After reading this, the article "what is the principle of SpringBoot automatic assembly in Java" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it to understand it. If you want to know more about related articles, 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