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 startup principle of springboot?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces "what is the startup principle of springboot". In daily operation, I believe many people have doubts about the startup principle of springboot. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what is the startup principle of springboot?" Next, please follow the editor to study!

Any Spring Boot project we develop will use the following startup class

@ SpringBootApplicationpublic 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

The @ SpringBootApplication annotation is the core annotation of SpringBoot, which is actually a combined annotation:

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

That is, @ SpringBootApplication = (default property) @ Configuration + @ 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@ComponentScanpublic 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:

First, the level of expression form

The XML-based configuration is as follows:

The JavaConfig-based configuration is as follows:

@ Configurationpublic class MockConfiguration {/ / bean definition}

Any Java class definition marked @ Configuration is a JavaConfig configuration class.

Second, the definition level of registration bean

The form of XML-based configuration is as follows:

...

The JavaConfig-based configuration looks like this:

@ Configurationpublic 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.

Third, express the dependency injection relationship

To express the dependency between bean and bean, it is generally like this in the XML form:

The JavaConfig-based configuration looks like this:

@ Configurationpublic 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.

@ Configuration: when you mention @ Configuration, you mention his partner @ Bean. Using these two annotations, you can create a simple spring configuration class that can be used to replace the corresponding xml configuration file.

Equivalent to:

@ Configuration public class Conf {@ Bean public Car car () {Car car = new Car (); car.setWheel (wheel ()); return car;} @ Bean public Wheel wheel () {return new Wheel ();}}

The annotated class of @ Configuration identifies that this class can use the Spring IoC container as the source of the bean definition.

The @ Bean annotation tells Spring that an annotated method with @ Bean will return an object that should be registered as a bean in the context of the Spring application.

@ 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.

The concept and way of doing things for @ EnableAutoConfiguration are actually in the same line, which can be summed up simply by collecting and registering bean definitions related to a particular scenario 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 is also with the help of @ Import to automatically configure everything.

@ EnableAutoConfiguration automatically configures the project according to the jar dependencies in the classpath. For example, if you add spring-boot-starter-web dependencies, you will automatically add Tomcat and Spring MVC dependencies, and Spring Boot will automatically configure Tomcat and Spring MVC.

As a composite Annotation, @ EnableAutoConfiguration defines the key information as follows:

Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Inherited@AutoConfigurationPackage@Import (AutoConfigurationImportSelector.class) public @ interface EnableAutoConfiguration {.}

The most important one is @ Import (AutoConfigurationImportSelector.class). With AutoConfigurationImportSelector@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 help of an original tool class of the Spring framework:

With the support of SpringFactoriesLoader, @ EnableAutoConfiguration can intelligently automatically configure the function to be completed!

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 get a corresponding set of @ Configuration classes based on the full class name org.springframework.boot.autoconfigure.EnableAutoConfiguration of @ EnableAutoConfiguration as the Key for lookup.

Automatic configuration

In the previous startup structure diagram, we noticed that both the application initialization and the specific execution process called the SpringBoot auto-configuration module.

SpringBoot automatic configuration module

The configuration module mainly uses SpringFactoriesLoader, that is, the Spring factory loader. The object provides the loadFactoryNames method. The input parameters are factoryClass and classLoader, that is, the factory class name in the above figure and the corresponding class loader need to be passed. According to the specified classLoader, the method will load the specified file under the search path of the class adder, that is, the spring.factories file, the incoming factory class is the interface, and the corresponding class in the file is the implementation class of the interface, or finally as the implementation class. Therefore, the file is generally a collection of one-to-many class names such as the following figure. After obtaining the class names of these implementation classes, the loadFactoryNames method returns the collection of class names. After the method callers get these collections, they obtain the class objects and constructors of these classes through reflection, and finally generate instances.

At this point, the study of "what is the startup principle of springboot" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Internet Technology

Wechat

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

12
Report