Spring boot automatic assembly principle

What does springboot automatically configure for us? What can we change?

Three core:

  • spring. Factories (various automatic configuration classes)
  • XXAutoConfiguration (autoconfiguration class)
  • Xxproperties (property injection modification)

1. Principle of automatic assembly (most important)

pom. Since the import of XML configuration, the core lies in the parent dependency. The dependency added later does not need version, because the parent dependency spring boot dependencies will perform version control.

1. Starter

One service will be turned into one launcher, which is an official jar package of springboot. The format is XXX spring boot. Of course, there are other packages such as XX boot spring

For example, springboot starter web service launcher, and others, such as jdbc starter


2. Load resources when springboot starts:

1. At startup, the springbootApplication annotation integrates many annotations to realize automatic assembly and load the loaded resources.

2. Click this annotation to see a * * @ EnableAutoConfiguration * * auto assembly annotation. Then click this annotation to see that an auto assembly class selector autoconfigurationimportselector is imported above class.

3. Click the AutoConfigurationImportSelector class, which helps you select which automatic assembly resources to load, including corresponding automatic assembly classes and static resources.

resourceLoader resource loader, which shows that all resources whose url starts with classPath will be loaded.

ClassLoader loads the of the class.

The konfigurationclassfilter is used to load the filter.

4. There is a method getCandidateConfigurations in the AutoConfigurationImportSelector, which indicates that it loads / meta-inf / spring The automatic assembly class of factories, and the condition can be loaded only if it is of EnableAutoConfiguration class.

  1. Finally, load meta-inf / spring.exe under auto configure package Configuration in factories * *

spring. All stored in factories are automatic configuration classes:

Properties properties=PropertiesLoaderUtils.loadProperties (resource);
All resources will be encapsulated into roperties For our configuration.

However, not all of the above automatic configurations can be automatically imported and take effect, because there is a key annotation @ ConditionalOnClass. Whether it is true or not should be judged according to the conditions. As long as the initiator corresponding to the corresponding start (start initiator in pom.xml) is imported, the corresponding configuration can be automatically imported! Then take effect!

Structure diagram

This part explains that the spring boot loads the core spin Factories file, which stores various automatic configuration classes.


spring.factories store the core classes to be loaded by springboot. From this file, we can see what to do when springboot starts.

Initialization = = = Application listener = = = auto configuration listener = = = auto configuration = = = Failure analyzers error analysis = = = = Template availability providers

Not all things need to be loaded. When loading these things, a comment @ conditionxx will check these automatic configuration classes. They will not be loaded until the conditions are met, at least POM XML needs to be imported before it can be started and loaded.

4. Deepen the principle

Generally, when we create a project, we need to import the package spring boot starter web at least. Then we can enter spring Facts will load the automatic configuration class webmvcoautoconfiguration.

1. You can see @ COnditionalOnClass in webmvcoautoconfiguration class, which will make some judgment conditions.

2. Let's take a look at what's in this WebAutoConfiguration and know what it can do?

//Partial member variable
private final WebMvcProperties mvcProperties;//Configuration classes related to the Properties property
private final ListableBeanFactory beanFactory;//bean related
private final ObjectProvider<DispatcherServletPath> dispatcherServletPath;//servlet related
private final ObjectProvider<ServletRegistrationBean<?>> servletRegistrations;

From the above, we can guess that this WebAutoConfiguration must have a configuration related class, which should specify the properties that we can configure through the configuration file. bean related must be the management of beans, and serlvet related is the route controller, including how to find the relationship between controller and route, and then the user enters a url, How does the background find the corresponding controller or servlet through the url.

The following are some of the member methods:

//path matching
		public void configurePathMatch(PathMatchConfigurer configurer) {
			if (this.mvcProperties.getPathmatch()
					.getMatchingStrategy() == WebMvcProperties.MatchingStrategy.PATH_PATTERN_PARSER) {
				configurer.setPatternParser(new PathPatternParser());
			this.dispatcherServletPath.ifAvailable((dispatcherPath) -> {
				String servletUrlMapping = dispatcherPath.getServletUrlMapping();
				if (servletUrlMapping.equals("/") && singleDispatcherServlet()) {
					UrlPathHelper urlPathHelper = new UrlPathHelper();

//bean name loading
public BeanNameViewResolver beanNameViewResolver() {
   BeanNameViewResolver resolver = new BeanNameViewResolver();
   resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
   return resolver;

	//Internal resource view loading
		public InternalResourceViewResolver defaultViewResolver() {
			InternalResourceViewResolver resolver = new InternalResourceViewResolver();
			return resolver;
//Format related
		public void addFormatters(FormatterRegistry registry) {
			ApplicationConversionService.addBeans(registry, this.beanFactory);

From these methods, we can know that this class can do path matching, internal resource loading and formatting.

There is an important internal class EnableWebMvcConfiguration, which implements the WebMvcConfigurer interface

Does that mean that we can also implement the WebMvcConfigurer interface and rewrite some methods????

Then, the internal class EnableWebMvcConfiguration is the default configuration that springboot implements for us. We can refer to it to rewrite the WebMvcConfigurer interface.

As shown in the following figure, some methods of the webmvcconfigurer interface can be rewritten and formatted, and the interceptor addinterctors can be added (you can't access the background management page without logging in).


We found a WebMvcProperties in the WebAutoConfiguration class above, which determines that we can properties can be configured.

As shown in the following figure, you can see in application The properties class uses * * @ ConfigurationProperties(prefix = 'spring.mvc') * * we can use the prefix spring mvc configures mvc related properties.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ral4jcas-1618463422375) (C: \ users \ mi \ appdata \ roaming \ typora \ typora user images \ image-20210415130201560. PNG)]

Not only the WebAutoConfiguration automatic configuration class has WebMvcProperties, but other automatic configuration classes also have xxProperties. According to xxProperties, we can know the application XML can be configured..

6. Attribute assignment

From the above example, WebMVCPropertie implements application through the annotation * * @ ConfigurationProperties(prefix = '') * * Properties can be configured. We can also customize a class and use application Properties to configure properties.

Keywords: Java Spring Boot

Added by markspec87 on Mon, 07 Mar 2022 21:22:31 +0200