Understanding the principle of automatic configuration in SpringBoot learning notes

Posted by vintox on Wed, 23 Feb 2022 16:51:00 +0100

Understand the principle of automatic configuration

1. SpringBoot features

1.1. Dependency management

  • Dependency management of parent project
Dependency management    
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
</parent>

His parent project
 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.3.4.RELEASE</version>
  </parent>

It declares the version number of almost all dependencies commonly used in development,Automatic version arbitration mechanism
  • Develop and import starter scenario launcher
1,See a lot spring-boot-starter-* :  *Just some kind of scene
2,Just introduce starter,We automatically introduce all the conventional dependencies of this scenario
3,SpringBoot All supported scenarios
https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter
4,See  *-spring-boot-starter:  The scenario launcher for simplified development provided by the third party.
5,The lowest level dependency of all scenario initiators
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
  <version>2.3.4.RELEASE</version>
  <scope>compile</scope>
</dependency>
  • No need to pay attention to the version number, automatic version arbitration
1,By default, no version can be written when importing dependencies
2,Introducing non version arbitration jar,Write the version number.
  • You can modify the default version number
1,see spring-boot-dependencies It specifies the current dependent version key. 
2,Rewrite the configuration in the current project
    <properties>
        <mysql.version>5.1.43</mysql.version>
    </properties>

1.2. Automatic configuration

  • Automatically configure Tomcat

    • Introduce Tomcat dependency
    • Configure Tomcat
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <version>2.3.4.RELEASE</version>
      <scope>compile</scope>
    </dependency>
  • Automatically configure spring MVC

    • Introduce a complete set of spring MVC components
    • Automatically configure common spring MVC components (functions)
  • Automatically configure common Web functions, such as character coding

    • SpringBoot helps us configure all the common scenarios for web development
  • Default package structure

    • The components in the package where the main program is located and all its sub packages will be scanned by default
    • No previous package scan configuration is required
    • To change the scanning path, @ SpringBootApplication(scanBasePackages = "com.atguigu")
    • Or @ ComponentScan specifies the scan path
@SpringBootApplication
 Equivalent to
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.atguigu.boot")
  • Various configurations have default values:

    • The default configuration is ultimately mapped to a class, such as MultipartProperties
    • The value of the configuration file will eventually be bound to each class, which will create objects in the container
  • Load all auto configuration items on demand

    • Very many starter s
    • What scenarios are introduced and the automatic configuration of this scenario will be enabled
    • All automatic configuration functions of spring boot are in the spring boot autoconfigure package

2. Container function

2.1. Component addition

1,@Configuration

  • Basic use

  • Full mode and Lite mode

  • Examples

  • Best practice

  • There is no dependency between configuration class components. Use Lite mode to accelerate the container startup process and reduce judgment

  • There are dependencies between configuration class components, and the method will be called to obtain the previous single instance component in Full mode

#############################Configuration Use example######################################################
/**
 * 1,The @ Bean annotation is used in the configuration class to register components for the container on the method. By default, it is also single instance
 * 2,The configuration class itself is also a component
 * 3,proxyBeanMethods: Method of proxy bean
 *      Full(proxyBeanMethods = true),[Ensure that the returned components of each @ Bean method are single instance]
 *      Lite(proxyBeanMethods = false)[How many times does each component return a new method
 *      Component dependencies must use the Full mode default. Are other default Lite modes available
 *
 *
 *
 */
@Configuration(proxyBeanMethods = false) //Tell SpringBoot that this is a configuration class = = configuration file
public class MyConfig {

    /**
     * Full:No matter how many external calls are made to this component registration method in the configuration class, the single instance object in the previous registration container is obtained
     * @return
     */
    @Bean //Add components to the container. Take the method name as the id of the component. The return type is the component type. The returned value is the instance of the component in the container
    public User user01(){
        User zhangsan = new User("zhangsan", 18);
        //The user component depends on the Pet component
        zhangsan.setPet(tomcatPet());
        return zhangsan;
    }

    @Bean("tom")
    public Pet tomcatPet(){
        return new Pet("tomcat");
    }
}


################################@Configuration The test code is as follows########################################
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.atguigu.boot")
public class MainApplication {

    public static void main(String[] args) {
        //1. Return to our IOC container
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);

        //2. View the components in the container
        String[] names = run.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }

        //3. Get component from container

        Pet tom01 = run.getBean("tom", Pet.class);

        Pet tom02 = run.getBean("tom", Pet.class);

        System.out.println("Components:"+(tom01 == tom02));


        //4,com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$51f1e1ca@1654a892
        MyConfig bean = run.getBean(MyConfig.class);
        System.out.println(bean);

        //If @ Configuration(proxyBeanMethods = true) the proxy object calls the method. SpringBoot always checks whether the component is in the container.
        //Keep component single instance
        User user = bean.user01();
        User user1 = bean.user01();
        System.out.println(user == user1);


        User user01 = run.getBean("user01", User.class);
        Pet tom = run.getBean("tom", Pet.class);

        System.out.println("User's pet:"+(user01.getPet() == tom));



    }
}

2,@Bean,@Component,@Controller,@Service,@Repository

@Component component, without explicit role, is used on the class

@Autowired can label class member variables, methods, constructors and parameters [mainly used on variables and methods] to complete automatic assembly.

@Service is used in the business logic layer (service layer)

@Repository is used in the data access layer (dao layer)

@The Controller is used in the presentation layer, and the declaration of the Controller (control layer)

@Beans are placed on methods, that is, let the methods generate a Bean, and then hand it over to the Spring container.

I don't know if you have ever thought that there are so many annotations for registering beans. Why do @ Bean annotations appear?

The reason is very simple: annotations such as @ component, @ repository, @ controller and @ service that register beans have limitations and can only be used on classes written by themselves. If a third-party library of a jar package wants to be added to the IOC container, these annotations have no binding power. Yes, the @ Bean annotation can do this!
Of course, in addition to @ Bean annotation, @ Import can also hand over class instances in third-party libraries to spring for management, and @ Import is more convenient and fast, but @ Import annotation is not within the scope of this article, so it will not be summarized here.

Another advantage of using @ Bean annotation is that it can dynamically obtain a Bean object and get different Bean objects according to different environments.

3,@ComponentScan,@Import

 * 4,@Import({User.class, DBHelper.class})
 *      Automatically create these two types of components in the container. The name of the default component is the full class name
 */

@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //Tell SpringBoot that this is a configuration class = = configuration file
public class MyConfig {
}

@Import advanced usage: Import advanced usage

4,@Conditional

Conditional assembly: component injection is performed when the conditions specified in conditional are met

=====================Test condition assembly==========================
@Configuration(proxyBeanMethods = false) //Tell SpringBoot that this is a configuration class = = configuration file
//@ConditionalOnBean(name = "tom")
@ConditionalOnMissingBean(name = "tom")
public class MyConfig {


    /**
     * Full:No matter how many external calls are made to this component registration method in the configuration class, the single instance object in the previous registration container is obtained
     * @return
     */

    @Bean //Add components to the container. Take the method name as the id of the component. The return type is the component type. The returned value is the instance of the component in the container
    public User user01(){
        User zhangsan = new User("zhangsan", 18);
        //The user component depends on the Pet component
        zhangsan.setPet(tomcatPet());
        return zhangsan;
    }

    @Bean("tom22")
    public Pet tomcatPet(){
        return new Pet("tomcat");
    }
}

public static void main(String[] args) {
        //1. Return to our IOC container
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);

        //2. View the components in the container
        String[] names = run.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }

        boolean tom = run.containsBean("tom");
        System.out.println("In container Tom Components:"+tom);

        boolean user01 = run.containsBean("user01");
        System.out.println("In container user01 Components:"+user01);

        boolean tom22 = run.containsBean("tom22");
        System.out.println("In container tom22 Components:"+tom22);


    }

2.2. Import of native configuration file

1,@ImportResource

======================beans.xml=========================
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="haha" class="com.atguigu.boot.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="18"></property>
    </bean>

    <bean id="hehe" class="com.atguigu.boot.bean.Pet">
        <property name="name" value="tomcat"></property>
    </bean>
</beans>



@ImportResource("classpath:beans.xml")
public class MyConfig {}

======================test=================
        boolean haha = run.containsBean("haha");
        boolean hehe = run.containsBean("hehe");
        System.out.println("haha: "+haha);//true
        System.out.println("hehe: "+hehe);//true

2.3. Configure binding

How to use Java to read the contents of the properties file and package it into JavaBean s for use at any time;

public class getProperties {
     public static void main(String[] args) throws FileNotFoundException, IOException {
         Properties pps = new Properties();
         pps.load(new FileInputStream("a.properties"));
         Enumeration enum1 = pps.propertyNames();//Get the name of the configuration file
         while(enum1.hasMoreElements()) {
             String strKey = (String) enum1.nextElement();
             String strValue = pps.getProperty(strKey);
             System.out.println(strKey + "=" + strValue);
             //Encapsulate into JavaBean s.
         }
     }
 }

1,@Component + @ConfigurationProperties

/**
 * Only the components in the container can have the powerful functions provided by SpringBoot
 */
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {

    private String brand;
    private Integer price;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}

====================application.properties===========================
mycar.brand=BYD;
mycar.price=10W;

2,@EnableConfigurationProperties + @ConfigurationProperties

@EnableConfigurationProperties(Car.class)
//1. Enable Car configuration binding function
//2. Automatically register the Car component into the container
public class MyConfig {
}


//@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {}

3. Introduction to automatic configuration principle

3.1. Boot loading automatic configuration class

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication{}


======================
    

1,@SpringBootConfiguration

@Configuration. Represents the current configuration class

2,@ComponentScan

Specify which Spring annotations to scan;

3,@EnableAutoConfiguration

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {}

3.1,@AutoConfigurationPackage

Auto configuration package? The default package rule is specified

@Import(AutoConfigurationPackages.Registrar.class)  //Import a component into the container
public @interface AutoConfigurationPackage {}

//Use the Registrar to import a series of components into the container for batch import
//Import all components under the specified package (under the package where MainApplication is located).

3.2,@Import(AutoConfigurationImportSelector.class)

1,utilize getAutoConfigurationEntry(annotationMetadata);Batch import some components into the container

2,call List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)Get all the configuration classes that need to be imported into the container

3,Using factory loading Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);Get all the components

4,from META-INF/spring.factories Location to load a file.
	By default, we can scan all in our current system META-INF/spring.factories Location file
    spring-boot-autoconfigure-2.3.4.RELEASE.jar It's also in the bag META-INF/spring.factories
    


It's dead in the file spring-boot As soon as you start, you need to give all the configuration classes loaded in the container

spring-boot-autoconfigure-2.3.4.RELEASE.jar/META-INF/spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration

3.2. Turn on the automatic configuration item as required

Although all the automatic configurations of our 127 scenarios are loaded by default when they are started. xxxxAutoConfiguration
 Assembly rules according to conditions(@Conditional),Finally, it will be configured on demand.

3.3. Modify the default configuration

        @Bean
		@ConditionalOnBean(MultipartResolver.class)  //There are components of this type in the container
		@ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) //There is no component with this name multipartResolver in the container
		public MultipartResolver multipartResolver(MultipartResolver resolver) {
            //If the method labeled @ Bean passes in the object parameter, the value of this parameter will be found from the container.
            //SpringMVC multipartResolver.  Prevent the file upload parser configured by some users from not conforming to the specification
			// Detect if the user has created a MultipartResolver but named it incorrectly
			return resolver;
		}
Add a file upload parser to the container;

SpringBoot will configure all components at the bottom by default. However, if the user has configured it himself, the user's priority shall prevail

@Bean
	@ConditionalOnMissingBean
	public CharacterEncodingFilter characterEncodingFilter() {
    }

Summary:

  • SpringBoot loads all the autoconfiguration classes xxxxconfiguration first

  • Each automatic configuration class takes effect according to conditions, and will bind the value specified in the configuration file by default. Take it from xxproperties. xxxProperties is bound to the configuration file

  • The effective configuration class will assemble many components in the container

  • As long as these components are in the container, they are equivalent to these functions

  • Customized configuration

    • Users directly replace the underlying components with @ Bean
    • The user can modify the value of the configuration file obtained by this component.

Xxxxxxautoconfiguration - > component - > xxxxproperties - > get the value - > application properties

3.4 best practices

  • Introduce scenario dependency

    • https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter
  • View which are automatically configured (optional)

    • After self analysis, the automatic configuration corresponding to the introduced scenario generally takes effect
    • debug=true in the configuration file enables the automatic configuration report. Negative \ Positive
  • Need to modify

    • Modify configuration item by referencing the document

    • https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#common-application-properties

    • Analyze yourself. Which of the configuration files are bound by xxproperties.

  • Custom add or replace components

    • @Bean,@Component. . .

    • Customizer xxxxxxcustomizer;

4. Development tips

4.1,Lombok

Simplify JavaBean development

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>


idea Search for installation in lombok plug-in unit
===============================simplify JavaBean development===================================
@NoArgsConstructor
//@AllArgsConstructor
@Data
@ToString
@EqualsAndHashCode
public class User {

    private String name;
    private Integer age;

    private Pet pet;

    public User(String name,Integer age){
        this.name = name;
        this.age = age;
    }


}



================================Simplify log development===================================
@Slf4j
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String handle01(@RequestParam("name") String name){
        
        log.info("The request came in....");
        
        return "Hello, Spring Boot 2!"+"Hello:"+name;
    }
}

4.2. Dev tools (hot update)

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

After modifying the item or page: Ctrl+F9; There is no need to restart the project

4.3. Spring Initailizr (project initialization wizard)

0. Select the development scenario we need

1. Automatic dependency import

2. Automatically create project structure

3. Automatically write the main configuration class

Reference articles

Explain Spring's @ bean annotation in vernacular

Spring annotation @ Autowired, @ Qualifier, @ Resource, @ Value

Silicon Valley Raytheon SpringBoot2 zero foundation entry springboot full set (spring boot2)

Topics: Java Spring Spring Boot