In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article shows you how SpringBoot works. It is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
Father dependence
Among them, it mainly depends on a parent project, which mainly manages the resource filtering and plug-ins of the project!
Org.springframework.boot spring-boot-starter-parent 2.2.5.RELEASE
Click in and find that there is still a father dependent.
Org.springframework.boot spring-boot-dependencies 2.2.5.RELEASE.. /.. / spring-boot-dependencies
This is the place to really manage all dependent versions in SpringBoot applications, the version control center of SpringBoot. Later, we do not need to write versions by default when we import dependencies; but if the imported packages are not managed in dependencies, you need to configure versions manually.
Initiator spring-boot-starter org.springframework.boot spring-boot-starter-web
Spring-boot-starter-xxx: the scene initiator of spring-boot
Spring-boot-starter-web: help us import the components that the web module depends on for normal operation.
SpringBoot extracts all the functional scenarios into individual starter (launchers). You only need to introduce these starter into the project, and all the related dependencies will be imported, and we can import what kind of scene launcher we want to use. We can also customize the starter in the future.
Main startup class
After analyzing the pom.xml, let's take a look at this startup class.
The default main startup class / * * @ author sowhat * @ create 2020-08-19 8:57 * / / to mark a main program class indicates that this is a SpringBoot application @ SpringBootApplicationpublic class HelloApp {public static void main (String [] args) {/ / thought a method was started, but unexpectedly started a service SpringApplication.run (HelloApp.class,args) }}
But a simple startup class is not easy! Let's analyze what these notes have done.
@ SpringBootApplication
Function: Mark on a class that this class is the main configuration class of SpringBoot, and SpringBoot should run the main method of this class to start the SpringBoot application
Enter this comment: you can see that there are many other comments on it!
@ Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Inherited@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan (excludeFilters = {@ Filter (type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @ Filter (type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class)}) public @ interface SpringBootApplication {....} @ ComponentScan
This annotation is important in Spring as it corresponds to the element in the XML configuration.
Purpose: automatically scan and load the eligible component or bean, loading this bean definition into the IOC container
@ SpringBootConfiguration
Function: SpringBoot configuration class, marked on a class, indicating that this is a SpringBoot configuration class
Let's go on to check this note.
@ Target ({ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Configurationpublic @ interface SpringBootConfiguration {@ AliasFor (annotation = Configuration.class) boolean proxyBeanMethods () default true;}
@ Configuration here indicates that this is a configuration class, and the configuration class is the xml configuration file corresponding to Spring.
The @ Component in it means that the startup class itself is just a component of Spring and is responsible for launching the application!
Let's go back to the SpringBootApplication comments and move on.
@ EnableAutoConfiguration
@ EnableAutoConfiguration: enable automatic configuration
We used to need our own configuration, but now SpringBoot can automatically configure it for us. @ EnableAutoConfiguration tells SpringBoot to turn on the auto-configuration feature so that the auto-configuration can take effect.
Click into the comments to continue to view:
@ AutoConfigurationPackage: automatically configure the package
@ import: Spring underlying annotation @ import to import a component into the container
Registrar.class function: scan the package of the main startup class and all the components in all the subpackages below the package to the Spring container
After this analysis, go back to the previous step and keep looking.
@ Import ({AutoConfigurationImportSelector.class}): import components to the container
AutoConfigurationImportSelector: automatically configure the import selector, so which component selector will it import? Let's click on this category to see the source code:
1. There is a method like this in this class
Call getAutoConfigurationEntry in selectImports to get the candidate configuration protected List getCandidateConfigurations (AnnotationMetadata metadata, AnnotationAttributes attributes) {/ / the getSpringFactoriesLoaderFactoryClass () method / / here returns the annotation class that we initially saw to start automatically importing configuration files; EnableAutoConfiguration 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. This method calls the static method of the SpringFactoriesLoader class again! Let's go into the loadFactoryNames () method of the Spring FactoriesLoader class
Public static List loadFactoryNames (Class factoryClass, @ Nullable ClassLoader classLoader) {String factoryClassName = factoryClass.getName (); / / here it calls the loadSpringFactories method return (List) loadSpringFactories (classLoader) .getOrDefault (factoryClassName, Collections.emptyList ());}
3. Let's continue to click to view the loadSpringFactories method
Private static Map loadSpringFactories (@ Nullable ClassLoader classLoader) {/ / get classLoader. What we can see here is the EnableAutoConfiguration annotated class itself MultiValueMap result = (MultiValueMap) cache.get (classLoader); if (result! = null) {return result;} else {try {/ / to get a resource "META-INF/spring.factories" Enumeration urls = classLoader! = null? ClassLoader.getResources ("META-INF/spring.factories"): ClassLoader.getSystemResources ("META-INF/spring.factories"); LinkedMultiValueMap result = new LinkedMultiValueMap (); / / traverses the read resource and encapsulates it into a Properties 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 factoryClassName = ((String) entry.getKey ()) .trim () String [] var9 = StringUtils.commaDelimitedListToStringArray ((String) entry.getValue ()); int var10 = var9.length; for (int var11 = 0; var11
< var10; ++var11) { String factoryName = var9[var11]; result.add(factoryClassName, factoryName.trim()); } } } cache.put(classLoader, result); return result; } catch (IOException var13) { throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13); } }} 4、发现一个多次出现的文件:spring.factories,全局搜索它 spring.factories 我们根据源头打开spring.factories , 看到了很多自动配置的文件;这就是自动配置根源所在! WebMvcAutoConfiguration 我们在上面的自动配置类随便找一个打开看看,比如 :WebMvcAutoConfigurationYou can see that these are all JavaConfig configuration classes, and they all inject some Bean, so you can find some classes you know and look familiar with them!
Therefore, 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.
Conclusion:
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.
Now we should have a general understanding of the operation principle of SpringBoot, and we will deepen it again later!
SpringApplication
Not a simple method.
At first, I thought I was running a main method, but I turned on a service instead.
/ / marking a main program class indicates that this is a SpringBoot application @ SpringBootApplicationpublic class HelloApp {public static void main (String [] args) {/ / thought a method was started, but unexpectedly a service SpringApplication.run (HelloApp.class,args);}}
SpringApplication.run analysis
The analysis of the method is mainly divided into two parts, one is the instantiation of SpringApplication, the other is the execution of run method.
SpringApplication
This class mainly does the following four things:
1. Infer whether the type of application is an ordinary project or a Web project
2. Find and load all available initializers and set them to the initializers property
3. Find all the application listeners and set them to the listeners attribute
4. Infer and set the definition class of the main method, and find the main class that runs
Check out the constructor (see this article for details):
Public SpringApplication (ResourceLoader resourceLoader, Class... PrimarySources) {this.resourceLoader = resourceLoader; Assert.notNull (primarySources, "PrimarySources must not be null"); this.primarySources = new LinkedHashSet (Arrays.asList (primarySources)); this.webApplicationType = WebApplicationType.deduceFromClasspath (); setInitializers ((Collection) getSpringFactoriesInstances (ApplicationContextInitializer.class)); setListeners ((Collection) getSpringFactoriesInstances (ApplicationListener.class)) This.mainApplicationClass = deduceMainApplicationClass ();} run method flow analysis
The above is how SpringBoot works. Have you learned any 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.