The article is very long, the expression is not good, hope can get ~~~~

Spring also provides the use of annotations to register beans, so why use SpringBoot?

Using Spring applications such as SpringMVC also requires configuration of ViewResolver, DispatcherServlet, and Mybatis.

The following is the spring-Mybatis configuration file:


      
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
 
	<! -- Import property configuration file -->
	<context:property-placeholder location="classpath:jdbc.properties" />
 
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
	</bean>
	<! Map data source to sqlSessionFactory
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
		<property name="dataSource" ref="dataSource" />
		<! --<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml" />-->
	</bean>
 
	<! SqlSession template class instance -->
	<bean id="sessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="close">
		<constructor-arg index="0" ref="sqlSessionFactory" />
	</bean>
 
	<! --======= transaction configuration Begin ================= -->
	<! -- Transaction manager (Spring manages MyBatis transactions) -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<! -- Associate data source -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<! --======= End =================== -->
	
	<! - mapper configuration - >
	<bean id="kbCityMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="mapperInterface" value="com.spring.dao.KbCityMapper" />
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>
</beans>
Copy the code

SpringBoot does the automatic configuration without requiring the user to do it. In addition, SpringBoot does not need to manage the version of dependency packages such as Mybatis, Log4j, and Jackson. SpringBoot uses starter for dependency management.

To use SpringBoot, just add a little configuration in application.yml or application. XML and start the application with @SpringBootApplication.

Let’s take a look at the Spring documentation

The point of auto-assembly is that SpringBoot initialized something for us ahead of time. Search the SpringBoot documentation for auto-configuration

For JSON Mapping libraries:

For Spring MVC:

You can see the automatic configuration of the BeanNameViewResolver.

For template engines:

You can see that Thymeleaf is automatically configured. We just need to import the Thymeleaf dependency and use it directly, without any configuration.

The Reids:

There are also Security, Spring Data, JPA, Elasticsearch, and many more. SpringBoot has pre-configured them so that we only need to import their dependencies, Yml requires little or no configuration and can be used directly.


Let’s take a look at the source of the JAR package

Let’s browse the spring-boot-Autoconfigure source code, so let’s look at the source code:

Let’s look at the meta-INF package and see what’s in the additional-spring-configuration-metadata.json file.

Let’s take a look at server.port:

Well, it defaults to 8080, doesn’t that sound familiar? Let’s go to our project’s application.properties

Then we’ll look at the server. The servlet. Encoding. Enabled, the server. The servlet. JSP. The class – the name of these two

Now we know that the default value in application.properties is derived from the additional-spring-configuration-metadata.json file.

Now look at the spring.factories file:

There are some complete classpath of AutoConfiguration class, so what can we do with a classpath? Of course, reflection creates the class. So there are so many auto-configuration classes that we’re not going to load all of them, so we’re going to load those with SpringBoot.

Spring-autoconfigure-metadata. properties: the left side of the equals sign indicates the classpath or property, and the right side indicates the classpath or value or empty. In order not to write these configuration properties dead in the code, extract them and put them in the properties file.

Spring-autoconfigure-metadata. json: I know the mapping between name and sourceType, type, and sourdestination. I don’t know what to do with it. Perhaps to make the value identified by name more legible in the code.

Keep reading:

You can see a lot of familiar names here. Let’s take a look at the Web package as an example:

These classes are roughly divided into two types: AutoConfiguration and Properties.

As an aside: We know that SpringBoot scans static resources in /resources/, /static/, /public/. Let’s look at WebProperties.java

Let’s take WebMvcProperties and WebMvcAutoConfiguration as examples.

WebMvcProperties: This property class completes the initialization of webMvc related properties.

Some properties are as follows:

	private String staticPathPattern = "/ * *";

	public static class Servlet {

		/** * Path of the dispatcher servlet. Setting a custom value for this property is not * compatible with the PathPatternParser matching strategy. */
		private String path = "/";
    
		public String getServletMapping(a) {
			if (this.path.equals("") | |this.path.equals("/")) {
				return "/";
			}
			if (this.path.endsWith("/")) {
				return this.path + "*";
			}
			return this.path + "/ *"; }}Copy the code

WebMvcAutoConfiguration: This class is initialized from the properties file using the get method.

Let’s take a look at it from the springbootApplication annotation

@SpringBootConfiguration: This is an @Configuration annotation, so the purpose of the SpringBootConfiguration annotation is to register the annotated class with Spring.

@ComponentScan: ComponentScan class, which is registered in Spring with controller, Service, Component annotation classes.

EnableAutoConfiguration: The main analysis below.

View the @ AutoConfigurationPackage:

Enter the AutoConfigurationPackages. The Registrar. Class:

Debug theregisterBeanDefinitionsMethods:

As you can see from the GIF above, the registerBeanDefinitions method should be to register all of our own package beans.

Then enter the AutoConfigurationImportSelector. Class:

Enter getAutoConfigurationEntry – > getCandidateConfigurations – > loadFactoryNames – > loadSpringFactories

You get the spring.Factories file, load it, and loop through it to put it into result.

We debug when we enter:

The result as a map, we take the org. Springframework. Boot. Autoconfigure. EnableAutoConfiguration as key, take out the size of 130 List < String >.

Now we came out from the getCandidateConfigurations, the configuration of the size 130 size, then go to heavy, ruled out.

In the execution getConfigurationClassFilter (). The filter (configurations); The size of the method’s front configurations is also 130.

After execution:

We ended up loading the 23 configuration classes.

How do I create my own starter?

The demo project was updated six years ago, using springboot1, which is a very old version. This example of poM dependency introduction is very complex, you can see others write automatic configuration class, quite complete.

Three points:

  • Pom files introduce springBoot dependencies.
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.4.5</version>
      <scope>compile</scope>
</dependency>
Copy the code
  • Create an automatic configuration class on which you must@ConfigurationOther binding notes may be added as appropriate
  • Write the auto-configuration class to the spring.factories file

It’s over.

🙂