SpringBoot technical overview

1. Origin


In order to cope with the increasingly complex enterprise-level application development, Spring came into being. Through dependency injection and aspect-oriented technology, it provides a relatively simple development method for enterprise-level Java development.

However, the birth of Spring cannot get rid of two major pain points:

  • Complex configuration management
  • Dependency management is cumbersome

Although Spring's components are lightweight, its related configuration is heavyweight. At the beginning, Spring uses complicated XML for configuration. In complex object scenarios, the workload of XML configuration is relatively cumbersome.

Later, Spring 2.5 introduced annotation-based component scanning, which eliminated a large number of explicit XML configurations; Spring 3.0 introduced Java-based configuration, which can better replace XML configuration with type safety.

Although the above evolution helps us reduce the burden of configuration, configuration work is still essential. For example, when using a three-party library, display configuration is required; transaction management and SpringMVC also need to use XML or Java for display configuration. Component scanning reduces the amount of configuration, and the Java configuration looks more refreshing. However, there is still a lot of Spring configuration work, which requires a lot of time and effort to complete.

In addition, the dependency management of the project is also relatively cumbersome. It is necessary to sort out the relevant dependency information required by the application and resolve the conflicts between dependencies. And the compatibility problems caused by relying on versions should not be underestimated.

Based on the above pain points, SpringBoot came into being.

2. Overview of the core points of SpringBoot


SpringBoot has brought about changes in Java development, the most important of which are the following four cores:

  • Automatic configuration : For many common application functions of Spring applications, Spring Boot can automatically provide relevant configurations
  • Start-up dependency : tell Spring Boot what functions are needed, and it can introduce the required libraries
  • Actuator : Allows you to drill down into a running Spring Boot application to find out
  • Command line interface : This is an optional feature of Spring Boot, so that you can complete a complete application by just writing code, without the need for traditional project construction
1. Automatic configuration

In traditional Spring projects, display configurations abound, such as code configuration snippets for JDBC accessing databases:

        @Bean
        public JdbcTemplate jdbcTemplate(DataSource dataSource) {
    
    
          return new JdbcTemplate(dataSource);
        }

This very simple Bean declaration creates an instance of JdbcTemplate and injects a DataSource dependency.

        @Bean
        public DataSource dataSource() {
    
    
          return new EmbeddedDatabaseBuilder()
                  .setType(EmbeddedDatabaseType.H2)
                  .addScripts('schema.sql', 'data.sql')
                  .build();
        }

These configurations are not complicated, but there are a large number of similar configuration fragments in many Spring applications. This large number of **boilerplate configuration** can be completed for us by relying on the automatic configuration of SpingBoot.

Taking the above scenario as an example, if Spring Boot finds the H2 database library in the application's Classpath, it will automatically configure an embedded H2 database.

If JdbcTemplate is found in the Classpath, it will also configure a JdbcTemplate Bean for you. You don't need to worry about the configuration of those beans, Spring Boot will be ready to inject it into your beans at any time. A method like this can greatly reduce the developer's configuration burden.

2. Start dependency

SpringBoot provides help for the dependency management of the project through the start-up dependency. The start-up dependency is aimed at Maven\Gradle through dependency transfer, and aggregates the dependency libraries related to specific functions to form a customized dependency set for specific functions.

In this way, developers are freed from complicated dependency configurations. During development, they only need to combine the functions to be implemented and introduce the relevant starting dependencies. They don’t need to care about which dependencies are introduced, which version of these dependencies to choose, etc., which is convenient. fast.
insert image description here

There are two major advantages to doing this:

  • Reduce the number of dependencies: only need to introduce starting dependencies
  • Safe and reliable: don't care about the version, the starting dependencies are all tested, and there will be no compatibility issues

If you want to know which dependencies are actually introduced, you can view them through the dependency tree of the build tool, or use Maven's dependency plugin command to view:

mvn dependency:tree

If you want to introduce a specific version for individual components, you can exclude the relevant transitive dependencies in the starting dependencies, and then explicitly and directly import them in POM.xml.

3、Actuator

Actuator provides the ability to inspect the internal operation of the application at runtime, mainly including the following details:

  • Beans configured in the Spring application context
  • Decisions made by Spring Boot's automatic configuration
  • Environment variables, system properties, configuration properties, and command-line parameters fetched by the application
  • The current state of the threads in the application
  • Tracking of recent HTTP requests processed by the application
  • Various metrics related to memory usage, garbage collection, web requests, and data source usage

You can send instructions through the relevant interface to view specific situation information.

3. Automatic configuration technology


1. Configure the startup boot class

First, there needs to be a configuration bootstrap class, which is the main Spring configuration class. While Spring Boot's auto-configuration eliminates a lot of Spring configuration, a small amount of configuration is required to enable auto-configuration:

@SpringBootApplication  // 开启组件扫描和应用配置
public class DemoApplication {
    
    

	public static void main(String[] args) {
    
    
		SpringApplication.run(DemoApplication.class, args);  // 负责启动引导应用程序
	}
}

@SpringBootApplication enables Spring's component scanning and Spring Boot's automatic configuration.

In effect, @SpringBootApplication combines three useful annotations.

  • @Configuration: Indicates that this class uses Spring's Java-based configuration. Although we won't write much about configuration in this book, we'll prefer Java-based configuration over XML.
  • @ComponentScan: Enables component scanning so that web controller classes and other components you write can be automatically discovered and registered as beans in the Spring application context. For example, the Spring MVC controller is annotated with @Controller so that component scanning can find it.
  • @EnableAutoConfiguration : It is this line of configuration that opens the magic of Spring Boot's automatic configuration, so that you don't have to write a whole article of configuration.

In the main method, a reference to the DemoApplication class and command line parameters are passed to SpringApplication.run() to start the application through these things.

2. Condition configuration

original

When we use SpringBoot, we can see a spring-boot-autoconfigure JAR file in the dependency library, which contains many configuration classes. These configuration classes will be in the application's ClassPath, according to the trigger conditions, for the application's automatic Configuration provides convenience:
insert image description here

These configuration classes can be flexibly loaded according to conditions because they use Spring's conditional configuration (a new feature introduced by Spring 4.0).

Conditional configuration allows configuration to exist in the application, but to ignore it until certain conditions are met. In addition, it is very easy to write your own conditions in Spring, all you have to do is implement the Condition interface and override its matches() method. For example, the following simple conditional class will only work if the JdbcTemplate exists on the classpath:

# 代码示例源自《SpringBoot实战》
public class JdbcTemplateCondition implements Condition {
    
    
  @Override
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    
    
    try {
    
    
       context.getClassLoader().loadClass("org.springframework.jdbc.core.JdbcTemplate");
       return true;
    } catch (Exception e) {
    
    
       return false;
    }
   }
}

When you declare beans in Java, you can use this custom condition class:

@Conditional(JdbcTemplateCondition.class)
public MyService myService() {
    
    
      ...
}

In this example, the MyService bean will only be created when the conditions of the JdbcTemplateCondition class are met. That is to say, the condition for MyService Bean to be created is that there is a JdbcTemplate in the Classpath. Otherwise, the Bean declaration will be ignored.

More conditional annotations are as follows:
insert image description here

3. Custom configuration
  • Override with display configuration

    The case comes from "SpringBoot Actual Combat"

insert image description here

When we show that the configuration of Spring Security has been written, Spring Boot will reduce the priority of automatic configuration, and the explicit configuration shall prevail.

The reason is that the @ConditionalOnMissingBean annotation is the key to overriding auto-configuration. We can see the following source code in the relevant automatic configuration:

        @Configuration
        @EnableConfigurationProperties
        @ConditionalOnClass({
    
     EnableWebSecurity.class })
        @ConditionalOnMissingBean(WebSecurityConfiguration.class)
        @ConditionalOnWebApplication
        public class SpringBootWebSecurityConfiguration {
    
    

        ...

        }

The @ConditionalOnMissingBean annotation requires that there is no Bean of type WebSecurityConfiguration at the moment. Although we did not explicitly create this Bean in the explicit configuration, by adding the @EnableWeb-Security annotation to SecurityConfig, we actually created a WebSecurityConfiguration Bean indirectly.

So during automatic configuration, this Bean already exists, the @ConditionalOnMissingBean condition is not satisfied, and the configuration provided by SpringBoot-WebSecurityConfiguration is skipped.

  • Fine-grained configuration using properties

    We perform fine-grained configuration of relevant properties in the application.properties file, or create a YAML file named application.yml for property configuration.

            spring.main.show-banner=false
    

    The yaml example is as follows:

            logging:
              level:
                root: INFO
    
            ---
    
            spring:
              profiles: development
    
            logging:
              level:
                root: DEBUG
    
            ---
    
            spring:
              profiles: production
    
            logging:
              path: /tmp/
              file: BookWorm.log
              level:
                root: WARN
    

    The application.yml file is divided into three sections, using a set of three hyphens (— ) as separators. The second and third paragraphs are the relevant configurations under different spring.profiles respectively, and the configurations of different parts will be activated under the corresponding profiles.

    Profile is generated in response to different application configurations and different deployment environments. This is a conditional configuration, based on the profile activated at runtime, different beans or configuration classes will be used or ignored.

            @Profile("production")
            @Configuration
            @EnableWebSecurity
            public class SecurityConfig extends WebSecurityConfigurerAdapter {
          
          
    
            ...
    
            }
    

    As shown above, the profile environment can be specified for the configuration class, and the above configuration class will be activated only when the profile is production, otherwise it will be ignored.

Reference: "SpringBoot in Action"

Guess you like

Origin blog.csdn.net/zhzh980/article/details/130069489