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

How to understand the core operation principle and source code of SpringBoot

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

How to understand the core operating principle and operating principle of SpringBoot source code, in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

The core operation principle of SpringBoot

The core function of Spring Boot is automatic configuration. As mentioned in Chapter 1, the implementation of functions is based on the principle that "convention is better than configuration". So how does Spring Boot agree, and how does it implement automatic configuration?

This chapter will lead you to learn the core operation principle of Spring Boot through the source code, including the operation principle of automatic configuration, core functional modules, core annotations and core source code analysis.

Core operation principle

When using SpringBoot, we only need to quote | into the corresponding Starters, and the SpringBoot will automatically load the relevant dependencies when it starts, configure the corresponding initialization parameters, and integrate the third-party software in the quickest and simplest form. This is the automatic configuration feature of SpringBoot. Let's first take a look at the core parts involved in Spring Boot's implementation of this operating mechanism as a whole, as shown in figure 2-1.

Figure 2-1 depicts several core functions involved in the operation of the Spring Boot autoconfiguration function and their relationships with each other, including @ EnableAutoConfiguration, spring.factories, corresponding AutoConfiguration classes for each component, @ Conditional annotations, and various Starters.

The whole process can be described in one sentence: Spring Boot enables automatic configuration through the @ EnableAutoConfiguration annotation and loads various AutoConfiguration classes registered in spring.factories. When an AutoConfiguration class meets the effective conditions specified by its annotation @ Conditional (dependency, configuration provided by Starters or whether a Bean exists in the Spring container, etc.), instantiate the Bean (components, etc.) defined in the AutoConfiguration class and inject the Spring container to complete the automatic configuration of the dependency framework.

Let's first take a conceptual and functional look at the functions and interrelationships of the parts shown in figure 2-1, which will be explained at the source code level for each function and component in later chapters.

@ EnableAutoConfiguration: this annotation is introduced by the combined annotation @ SpringBootApplication to enable the automatic configuration, scan the spring.factories files under each jar package, and load the AutoConfiguration classes registered in the files.

Spring.factories: the configuration file, located in the META-INF directory of the jar package, registers the automatically configured AutoConfiguration class in the specified format. Spring.factories can also contain other types of classes to be registered. This configuration file exists not only in Spring Boot projects, but also in custom autoconfiguration (or Starter) projects.

AutoConfiguration class: an autoconfiguration class that represents a class of autoconfiguration classes named after XXAutoConfiguration in Spring Boot. The Bean and conditions needed to initialize the integration of three-party components into Spring are defined.

Conditional: conditional annotations and their derivative annotations are used on the AutoConfiguration class, and the AutoConfiguration class is instantiated only when the conditional annotations are met.

Starters: the dependency and configuration of tripartite components, components that have been preset by Spring Boot. Spring Boot default Starters projects tend to contain only one project that pom depends on. If it is a custom starter, the project also needs to include spring.factories files, AutoConfiguration classes, and other configuration classes.

The above introduces the overall process and basic operation principle of Spring Boot automatic configuration at the conceptual level, and the structure and source code of these core parts will be described in detail below.

Operating principle source code parsing Z@EnableAutoConfiguration

@ EnableAutoConfiguration is an annotation that turns on automatic configuration, which is not directly visible in the created SpringBoot project, but is introduced by the combined annotation @ SpringBootApplication. Let's take a look at the functions of the entry class and the @ SpringBootApplication annotation, and then take a closer look at the composition and function of the @ EnableAutoConfiguration annotation.

Entry class and @ SpringBootApplication annotation

When the Spring Boot project is created, a * Application entry class is generated by default. By default, whether you create a Maven-based Spring Boo project through IDEA or officially, the naming convention for the portal class is artifactld+Application. The Spring Boot project can be started through the main method of this class, as follows.

@ SpringBootApplication public class SpringLearnApplication {public static void main (String [] args) {SpringApplication. Run (DemoApplication. Class, args);}}

There is nothing special about the main method here, which is a standard main method for Java applications, which is used to launch the entrance to the SpringBoot project. By default, classes that are named according to the above rules and contain main methods are called entry classes.

The only annotation in the SpringBoot entry class (except for unit tests) is @ SpringBootApp-lication.

It is the core annotation of the Spring Boot project and is used to enable autoconfiguration, which is precisely enabled through the @ EnableAutoConfiguration combined within the annotation.

Part of the source code for @ SpringBootApplication is as follows. @ Target (ElementType. TYPE) @ Retent ion (Retent ionPolicy. RUNTIME) @ Documented @ Inherited @ SpringBootConfiguration @ EnableAutoConfi guration @ ComponentScan (excludeFilters = {@ Filter (type = FilterType .custom, classes = TypeExcludeFilter. Class), @ Filter (type = FilterType. CUSTOM, classes = AutoConf igurationExcludeFilter. Class) public @ interface SpringBootApplication {/ / exclude the specified autoconfiguration class @ AliasFor (annotation = EnableAutoConfiguration.class) Class [] exclude () default {}; / / exclude the specified autoconfiguration class name @ AliasFor (annotation = EnableAutoConfiguration. Class) String [] excludeName () default {/ / specify the base package for scanning, and activate the initialization @ AliasFor (annotation = ComponentScan. Class, attribute = "basePackages") String [] scanBasePackages () default {}; / / specify the scanning class, which is used to initialize @ AliasFor (annotation = ComponentScan.) Class, attribute = "basePackageClass Class [] scanBasePackageClasses () default {}; / / specify whether to proxy the @ Bean method to enforce the lifecycle behavior of bean @ AliasFor (annotation = Configuration.class) boolean proxyBeanMethods () default true;}

As you can see from the source code, the annotation provides the following member attributes (the member variables in the annotation are represented in the form of methods).

Exclude: excludes the specified autoconfiguration based on the class (Class), which overrides the exclude member attribute defined in @ EnableAutoConfiguration combined in @ SpringBoot-Application.

ExcludeName: excludes the specified autoconfiguration based on the class name, overriding the member attribute of excludeName in @ EnableAutoConfiguration.

: scanBasePackages: specify the base package of the scan, which is used to activate the initialization of annotated classes such as @ Component.

ScanBasePackageClasses: scans the specified class for component initialization.

: proxyBeanMethods: specifies whether to proxy the @ Bean method to enforce the lifecycle behavior of bean. This feature requires method interception by generating CGLIB subclasses at run time. This subclass has certain restrictions, such as configuration classes and their methods are not allowed to be declared as final, and so on.

The default value of proxyBeanMethods is true, which allows inter-beanreferences (references between bean) and external calls to the @ Bean method of the configuration class. If the @ Bean methods are self-contained and only provide the functionality of the normal engineering methods used by the container, you can set it to false to avoid dealing with the CGLIB subclass. After the launch of SpringBoot 2.2, this member attribute is added. ProxyBeanMethods is basically used in the automatic configuration classes covered in the following chapters, and in the same case, it is configured as false.

From the above source code, we will find that the @ AliasFor annotation is heavily used in Spring Boot, which is used to bridge to other annotations, and the attribute of the annotation specifies the bridged annotation class. If you click on it, you will find that the attributes defined by @ SpringBootApplication have already been defined in other annotations. The reason for using @ AliasFor annotations and redefining them in @ SpringBootApplication is more to reduce the hassle caused by users using multiple annotations.

@ SpringBootApplication

@ SpringBootConfiguration, @ EnableAutoConfiguration, and @ ComponentScan are grouped in the annotation. Therefore, you can also use these three annotations to replace @ SpringBootApplication in practice.

There is no @ SpringBootConfiguration annotation in earlier versions of SpringBoot, and @ SpringBootConfiguration has been added and combined with @ Configuration after the upgrade.

@ EnableAutoConfiguration annotations combine @ AutoConfigurationPackage. We have ignored some basic annotations and meta annotations, and the combined structure of @ SpringBootApplication annotations can be seen in figure 2-2.

In figure 2-2, in addition to combinatorial meta-annotations, the core functions of @ SpringBootApplication include activating @ EnableAutoConfiguration for SpringBoot automatic configuration, @ ComponentScan for activating @ Component scanning, and @ Configuration for configuration classes.

Among them, @ ComponentScan annotations and @ Configuration annotations are often used in the daily use of Spring, and they are also very basic. Everyone should have some solutions, so there will be no more details here. The following details introduce the functions of @ EnableAuto-Configuration.

Annotation @ EnableAutoConfiguration function parsing

Without Spring Boot, the lifecycle of Bean is managed by Spring, but Spring cannot automatically configure @ Configuration annotated classes. One of the core functions of Spring Boot is to automatically manage the annotated classes according to the convention. One of the components used to implement this function is the @ EnableAutoConfiguration annotation.

@ EnableAutoConfiguration is located in the spring-boot autoconfigure package, and when you use the @ SpringBootApplication annotation, the @ EnableAutoConfiguration annotation takes effect automatically.

The main function of @ EnableAutoConfiguration is to automatically configure when you start the Spring application context, which attempts to guess and configure the Bean that the project might need. Automatic configuration is usually implemented based on the classes introduced in the project classpath and the defined Bean. During this process, the components that are automatically configured come from the project itself and from the jar package on which the project depends.

For example: if you add tomcat-embedded.jar to classpath, @ EnableAutoConfiguration will think you are ready to use the TomcatServletWebServerFactory class and help you initialize the configuration. At the same time, if you customize the ServletWebServerFactory-based Bean, @ EnableAutoConfiguration will not initialize the TomcatServletWebServerFactory class. This series of operational judgments are completed by Spring Boot.

Let's take a look at the source code of the @ EnableAutoConfiguration annotation.

@ Target (ElementType. TYPE) @ Retention (RetentionPolicy. RUNTIME) @ Documented @ Inherited @ AutoConfigurationPackage @ Import (AutoConfigurat ionImportSelector. Class) public @ interface EnableAutoConfiguration {/ / is used to configure the automatic configuration function String ENABLED. OVERRIDE_ PROPERTY = "spring. Boot. Enableautoconf iguration"; / / exclude specified autoconfiguration Class [] exclude () default {} based on class (Class); / / exclude specified autoconfiguration String [] excludeName () autoconfiguration {};} based on class name

The @ EnableAutoConfiguration annotation provides definitions of one constant and two member parameters.

ENABLED OVERRIDE PROPERTY: used to override the ability to turn autoconfiguration on / off.

-exclude: excludes specified autoconfiguration based on class (Class).

ExcludeName: excludes the specified autoconfiguration based on the class name.

As mentioned above, @ EnableAutoConfiguration will guess the Bean you need to use, but if you do not need it to preset the initialized Bean in practice, you can specifically exclude it through the exclude or excludeName parameters of the annotation. For example, when automatic configuration of a database is not required, it can be invalidated in two ways.

/ / exclude DataSourceAutoConfiguration @ SpringBootApplication (exclude = DataSourceAutoConfiguration.class) public class SpringLearnApplication {} through @ SpringBootApplication or: / / exclude DataSourceAutoConfiguration @ Configuration@EnableAutoConfiguration (exclude = DataSourceAutoConfiguration.) through @ EnableAutoConfiguration. Class) public class DemoConfiguration {}

It is important to note that the package of the class annotated by @ EnableAutoConfiguration also has a specific meaning and is usually used as the root path for scanning the annotation @ Entity. This is why you need to put the annotated class under the top-level package when using the @ SpringBootApplication annotation, and if you put it at a lower level, the class in the sibling or parent of its package cannot be scanned.

For the entry class and its main method, it does not rely on the @ SpringBootApplication annotation or the @ EnableAuto-Configuration annotation, which means that the annotation can be used on other classes rather than on the entry class.

This is the answer to the question about how to understand the core operation principle and the source code of SpringBoot. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

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