In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 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 Spring Boot startup", the content is detailed, the steps are clear, and the details are handled properly. I hope this article "what is the principle of Spring Boot startup" can help you solve your doubts.
Any Spring Boot project we develop will use the following startup class
@ SpringBootApplication
Public class Application {
Public static void main (String [] args) {
SpringApplication.run (Application.class, args)
}
}
As you can see from the above code, the Annotation definition (@ SpringBootApplication) and the class definition (SpringApplication.run) are the most dazzling, so to unravel the mystery of SpringBoot, we need to start with these two.
The secret behind SpringBootApplication
@ 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 {
...
}
Although the definition uses multiple Annotation to annotate the original information, in fact only three Annotation are important:
@ Configuration (click @ SpringBootConfiguration to check and find that @ Configuration is still applied)
@ EnableAutoConfiguration
@ ComponentScan
Therefore, if we use the following SpringBoot startup class, the entire SpringBoot application can still be functional equivalent to the previous startup class:
@ Configuration
@ EnableAutoConfiguration
@ ComponentScan
Public class Application {
Public static void main (String [] args) {
SpringApplication.run (Application.class, args)
}
}
It's tiring to write these three at a time, so it's convenient to write a @ SpringBootApplication. Next, we introduce these three Annotation respectively.
@ Configuration
The @ Configuration here is not new to us. The @ Configuration,SpringBoot community that uses the configuration class of the Spring Ioc container in the form of JavaConfig recommends using the JavaConfig-based configuration form. Therefore, after the startup class here is marked with @ Configuration, it is actually a configuration class of the IoC container.
To review a few simple examples, the difference between XML and config configuration:
Expression form level
The XML-based configuration is as follows:
The JavaConfig-based configuration is as follows:
@ Configuration
Public class MockConfiguration {
/ / bean definition
}
Any Java class definition marked @ Configuration is a JavaConfig configuration class.
Register the bean definition level
The form of XML-based configuration is as follows:
...
The JavaConfig-based configuration looks like this:
@ Configuration
Public class MockConfiguration {
@ Bean
Public MockService mockService () {
Return new MockServiceImpl ()
}
}
The return value of any method marked with @ Bean will be registered with the Spring's IoC container as a bean definition, and the method name will default to the id of that bean definition.
Express dependency injection relationship level
To express the dependency between bean and bean, it is generally like this in the XML form:
The JavaConfig-based configuration looks like this:
@ Configuration
Public class MockConfiguration {
@ Bean
Public MockService mockService () {
Return new MockServiceImpl (dependencyService ())
}
@ Bean
Public DependencyService dependencyService () {
Return new DependencyServiceImpl ()
}
}
If the definition of a bean depends on other bean, you can simply call the creation method that depends on bean in the corresponding JavaConfig class.
@ ComponentScan
The @ ComponentScan annotation is important in Spring because it corresponds to the elements in the XML configuration. The function of @ ComponentScan is to automatically scan and load eligible components (such as @ Component and @ Repository, etc.) or bean definitions, and finally load these bean definitions into the IoC container.
We can fine-grained customize the scope of @ ComponentScan automatic scanning through attributes such as basePackages. If not specified, the default Spring framework implementation will scan from the package that declares the class of @ ComponentScan.
Note: therefore, the startup class of SpringBoot is best placed under root package, because basePackages is not specified by default.
@ EnableAutoConfiguration
I feel that @ EnableAutoConfiguration is the most important Annotation, so in the end, do you remember the various Annotation definitions with names starting with @ Enable provided by the Spring framework? For example, @ EnableScheduling, @ EnableCaching, @ EnableMBeanExport, etc., @ EnableAutoConfiguration has the same philosophy and way of doing things. To sum up, it collects and registers bean definitions related to specific scenarios with the support of @ Import.
@ EnableScheduling loads all the bean definitions related to the Spring scheduling framework into the IoC container through @ Import.
@ EnableMBeanExport loads JMX-related bean definitions into the IoC container through @ Import.
And @ EnableAutoConfiguration loads all bean definitions that meet the automatic configuration criteria into the IoC container with the help of @ Import, that's all!
As a composite Annotation, @ EnableAutoConfiguration defines the key information as follows:
@ SuppressWarnings ("deprecation")
@ Target (ElementType.TYPE)
@ Retention (RetentionPolicy.RUNTIME)
@ Documented
@ Inherited
@ AutoConfigurationPackage
@ Import (EnableAutoConfigurationImportSelector.class)
Public @ interface EnableAutoConfiguration {
...
}
The most important one is @ Import (EnableAutoConfigurationImportSelector.class). With EnableAutoConfigurationImportSelector,@EnableAutoConfiguration, you can help SpringBoot applications load all eligible @ Configuration configurations into the IoC container created and used by SpringBoot. Just like an octopus.
With the support of SpringFactoriesLoader, an original tool class of the Spring framework, @ EnableAutoConfiguration can intelligently configure automatically.
Automatic configuration of behind-the-scenes heroes: SpringFactoriesLoader details
SpringFactoriesLoader is an extension scheme proprietary to the Spring framework, and its main function is to load the configuration from the specified configuration file META-INF/spring.factories.
Public abstract class SpringFactoriesLoader {
/ /...
Public static List loadFactories (Class factoryClass, ClassLoader classLoader) {
...
}
Public static List loadFactoryNames (Class factoryClass, ClassLoader classLoader) {
....
}
}
When used with @ EnableAutoConfiguration, it is more likely to provide a function of configuration lookup, that is, to obtain a corresponding set of @ configuration classes according to the full class name of @ EnableAutoConfiguration, org.springframework.boot.autoconfigure.EnableAutoConfiguration, as the Key for lookup.
The above figure is an excerpt from the META-INF/spring.factories configuration file in SpringBoot's autoconfigure dependency package, which is a good illustration.
So, the magic knight automatically configured by @ EnableAutoConfiguration becomes: search for all META-INF/spring.factories configuration files in classpath, and instantiate the corresponding configuration items of org.springframework.boot.autoconfigure.EnableutoConfiguration into corresponding IoC container configuration classes marked @ Configuration in the form of JavaConfig through Java Refletion, and then aggregate them into one and load them into the IoC container.
In-depth exploration of SpringApplication execution process
The implementation of SpringApplication's run method is the main route of our journey, and the main flow of this method can be summarized as follows:
1) if we are using the static run method of SpringApplication, we first create an instance of the SpringApplication object in this method, and then call the instance method of the created SpringApplication. When the SpringApplication instance is initialized, it does several things in advance:
Depending on whether there is a feature class (org.springframework.web.context.ConfigurableWebApplicationContext) in classpath, you can decide whether you should create an ApplicationContext type for Web applications.
Use SpringFactoriesLoader to find and load all available ApplicationContextInitializer in the application's classpath.
Use SpringFactoriesLoader to find and load all available ApplicationListener in the application's classpath.
Infer and set the definition class of the main method.
2) after the initialization and setup of the SpringApplication instance is completed, the logic of the run method is executed. At the beginning of the method execution, all the SpringApplicationRunListener that can be found and loaded through the SpringFactoriesLoader is traversed. Call their started () method and tell the SpringApplicationRunListener, "Hey, the SpringBoot app is about to start executing!" .
3) create and configure the Environment that the current Spring Boot application will use (including configuring the PropertySource and Profile to be used).
4) iterate through the methods that call all SpringApplicationRunListener's environmentPrepared (), telling them: "the Environment used by the current SpringBoot application is ready!" .
5) if the showBanner property of SpringApplication is set to true, banner is printed.
6) according to whether the user has clearly set the applicationContextClass type and the inference results of the initialization phase, decide what type of ApplicationContext should be created for the current SpringBoot application and complete the creation, and then decide whether to add ShutdownHook according to the conditions, decide whether to use custom BeanNameGenerator, decide whether to use custom ResourceLoader, and of course, most importantly, set the previously prepared Environment to the created ApplicationContext.
7) after the ApplicationContext is created, SpringApplication will again find and load all the available ApplicationContext-Initializer in the classpath with the help of Spring-FactoriesLoader, and then iterate through the initialize (applicationContext) methods that call these ApplicationContextInitializer to further process the ApplicationContext that has been created.
8) iterate through and call all SpringApplicationRunListener's contextPrepared () methods.
9) the core step is to load all the configurations previously obtained through @ EnableAutoConfiguration and other forms of IoC container configuration into the prepared ApplicationContext.
10) iterate through and call all SpringApplicationRunListener's contextLoaded () methods.
11) call the refresh () method of ApplicationContext to complete the last process available to the IoC container.
12) find out if CommandLineRunner is registered in the current ApplicationContext, and if so, traverse and execute them.
13) normally, iterate through the finished () method that executes SpringApplicationRunListener (if there is an exception in the whole process, the finished () method of all SpringApplicationRunListener will still be called, but in this case the exception information will be passed in as well)
After reading this, the article "what is the principle of Spring Boot startup" 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, 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.