@[toc]

First, basic use of SpringBoot

The SpringBoot framework is so large and feature-rich that it is basically the de facto standard for where J2EE development is headed today. The ecosystem expanded by SpringBoot covers almost all technical directions. There are hundreds of easy ways to use SpringBoot, but what is SpringBoot really like? Which features are Spring and which are SpringBoot? How to fully and deeply learn and grasp the SpringBoot framework? A lot of times it’s actually very vague. This list is just a few study notes for learning the basics of the SpringBoot framework. Some are self-written, some are collected online. It will focus more on the bottom line, and there will be a brief introduction to the use of SpringBoot, but it will not be the focus. You can track the process by building a simple SpringBoot project.

2. Overall understanding of SpringBoot

The whole functionality of the SpringBoot framework is condensed into the spring.factories file. After we create SpringBoot engineering, will introduce a mave dependence: org. Springframework. The boot: spring – the boot – starter: 2.4.5. This dependency is the cornerstone of SpringBoot. The spring-boot-2.4.5.jar package contains the spring.factories configuration file. The SpringBoot framework expands all of its functionality around this configuration file.

Here is the latest stable version 2.4.5 to test

Open up the contents of the file, which is essentially a key-value configuration file, and it looks something like this

# Logging Systems
org.springframework.boot.logging.LoggingSystemFactory=.
# PropertySource Loaders
org.springframework.boot.env.PropertySourceLoader=.
# ConfigData Location Resolvers
org.springframework.boot.context.config.ConfigDataLocationResolver=.
# ConfigData Loaders
org.springframework.boot.context.config.ConfigDataLoader=.
# Run Listeners
org.springframework.boot.SpringApplicationRunListener=.
# Error Reporters
org.springframework.boot.SpringBootExceptionReporter=.
# Application Listeners
org.springframework.context.ApplicationListener=.
# Environment Post Processors
org.springframework.boot.env.EnvironmentPostProcessor=.
# Failure Analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=.
# Failure Analysis Reporters
org.springframework.boot.diagnostics.FailureAnalysisReporter=.

Copy the code

Now let’s understand this configuration file: First, each configuration in this configuration file corresponds to a mechanism provided by SpringBoot. This configuration file, in form, can be easily understood as a Java-like SPI extension mechanism configuration file. Each key corresponds to a functional interface, and the following values correspond to multiple implementations of that interface. However, the implementation of the function here does not refer to all the interface implementation classes in Java, but to the core implementation classes related to this function, which will be explained in detail later. Many functions can also be roughly understood from the interface name. For example org. Springframework. Context. The ApplicationListener corresponding SpringBoot events to monitor function. Org. Springframework. Context. The framework of the corresponding SpringBoot ApplicationContextInitializer startup initialization function. The process mechanisms for loading and working are different for each feature, but they make up the SpringBoot framework as a whole. These features are where we need to start to understand the SpringBoot framework as a whole. Then: The profile is extensible. Maven rely on the basis of SpringBoot org. Springframework. The boot: spring – the boot – starter: 2.4.5, Also contains a basic rely on other org. Springframework. The boot: spring – the boot – autoconfigure: 2.4.5. There is also a spring.factories file under the corresponding JAR package for this dependency. The structure looks something like this:

# Initializers
org.springframework.context.ApplicationContextInitializer=.
# Application Listeners
org.springframework.context.ApplicationListener=.
# Auto Configuration Import Listeners
org.springframework.boot.autoconfigure.AutoConfigurationImportListener=.
# Auto Configuration Import Filters
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=.
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=.
# Failure analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=.
# Template availability providers
org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=.
Copy the code

He adds some configuration to the spring.factories file from the spring-boot-starter. Together, it is these configurations that enable SpringBoot to automate its assembly. In other words, SpringBoot scans all META/spring.factories in the ClassPath, pulls them together to form the basic features of the project, and uses these configurations as a basis for implementing different features.

Of course, there are so many extension mechanisms that SpringBoot implements that the spring.factories file based extension is rarely used during actual development. However, this is really the core of the SpringBoot framework. In addition, there are many components within the SpringBoot framework that are extended through this mechanism. Since this extension mechanism is available within the framework, it is also available when we use the SpringBoot framework.

3. SpringBoot SPI loading mechanism

The rest of the section follows this configuration file function one by one. Before you start, it’s important to know how SpringBoot loads these configurations. Mentioned above the whole spring. Factories file loading process, all in the org. Springframework. Core. IO. Support. This class that SpringFactoriesLoader belongs to the jar package: Spring – the core – 5.3.6. Jar. Take a look at his loadSpringFactories method.

		private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
		Map<String, List<String>> result = cache.get(classLoader);
		if(result ! =null) {
			return result;
		}

		result = new HashMap<>();
		try {
			Enumeration<URL> urls = classLoader.getResources(FACTORIES_RESOURCE_LOCATION);
			while (urls.hasMoreElements()) {
				URL url = urls.nextElement();
				UrlResource resource = new UrlResource(url);
				Properties properties = PropertiesLoaderUtils.loadProperties(resource);
				for(Map.Entry<? ,? > entry : properties.entrySet()) { String factoryTypeName = ((String) entry.getKey()).trim(); String[] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray((String) entry.getValue());for (String factoryImplementationName : factoryImplementationNames) {
						result.computeIfAbsent(factoryTypeName, key -> newArrayList<>()) .add(factoryImplementationName.trim()); }}}// Replace all lists with unmodifiable lists containing unique elements
			result.replaceAll((factoryType, implementations) -> implementations.stream().distinct()
					.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)));
			cache.put(classLoader, result);
		}
		catch (IOException ex) {
			throw new IllegalArgumentException("Unable to load factories from location [" +
					FACTORIES_RESOURCE_LOCATION + "]", ex);
		}
		return result;
	}
Copy the code

Under this class, you can also look for specific implementation classes by interface and classloader. But this is the core approach. This is the basis for reading configuration information throughout SpringBoot.

Then in a web only contains a simple spirngBoot dependence (Maven rely on org. Springframework. The boot: spring – the boot – starter – web) project started, and in return the result of this method, a line add a breakpoint, You can see that SpringBoot loads the spring.factories configuration with 16 by default.

There were only 13 in version 2.2.3 and 16 in version 2.4.5.

These 16 configurations correspond to SpringBoot’s 16 core function points. The transition from Spring to SpringBoot is completed by adding implementation classes after each function point. And these 16 function points, that is, the focus of the rear to comb. Later strive to comb this each function point, I believe that through such a comb, will be able to use SpringBoot in the process of a variety of puzzling “secrets” have an overall grasp.

Found a lot of articles online, a lot of function points have, but very scattered. The explanations for SpringBoot are also mostly focused on any use, with few explanations of the core implementation mechanism for these function points. Here when the collection of summary, plus some of their own understanding.