[Spring Boot] Basic introduction and analysis

1.SpringBoot Overview

  • SpringBoot is introduced by Spring
    If you are a Java developer, Spring is unlikely to be unfamiliar to you. When we first use Spring, we will find that its component code is lightweight . This is also its original design intention, but during use , as business develops, the technologies used and the dependencies between technologies become more and more, and their configurations become more and more heavyweight .
    In the beginning, Spring used XML configuration , and a lot of XML configuration. Spring 2.5 introduces annotation -based component scanning, which eliminates a lot of explicit XML configuration for the application's own components. Spring 3.0 introduces Java-based configuration , a type-safe, reconfigurable alternative to XML. But no matter which configuration method is used, it will ultimately take a lot of time for developers to solve technical configuration problems by themselves.
    Secondly, although we now have many good project dependency management tools , such as Maven, Ant, etc., they can help us quickly obtain and manage the corresponding dependencies, but they cannot help us solve the compatibility between dependencies at the beginning. Problem , this kind of problem is sometimes not easy to find, nor is it easy to locate quickly.
    All the above questions have an answer in SpringBoot.

  • SpringBoot features
    SpringBoot improves and optimizes the above-mentioned Spring shortcomings, based on the idea that convention is better than configuration , so that developers do not have to switch their thinking between configuration and logical business, and can devote themselves wholeheartedly to writing code for logical business, thus It greatly improves the efficiency of development and shortens the project cycle to a certain extent.
    A brief introduction to the concept of convention over configuration: Learn about convention over configuration in one minute.
    SpringBoot has the following four specific characteristics:
    • Provide a faster onboarding experience for Spring-based development
    • Works out of the box with no code generation and no XML configuration required. The default values ​​can also be modified to meet specific needs.
    • Provides some non-functional features common in large projects, such as embedded servers, security, indicators, health detection, external configuration, etc.
    • SpringBoot is not an enhancement to Spring's functionality, but provides a way to quickly use Spring.

  • SpringBoot core functions
    The specific core functions will be explained in detail later when writing code, only an overview is given here.
    • Starter dependency (simplifying dependency configuration and solving compatibility issues between dependencies)
      Starter dependency is essentially a Maven Project Object Model (POM), which defines transitive dependencies on other libraries. Together, these things support a certain item Function.
      Simply put, the starting dependency is to package coordinates with certain functions together and provide some default functions.
    • Automatic configuration (solve heavyweight configuration problems)
      Spring Boot's automatic configuration is a runtime (more accurately, when the application starts) process. Many factors are considered to decide which Spring configuration should be used and which one should not be used. . This process is completed automatically by Spring.

2.SpringBoot project creation

  • Maven creates SpringBoot project

First, use the idea tool to create a maven project. This project is an ordinary java project and does not use the Maven skeleton.
Insert image description here
Next, give it a name and complete the creation.
Insert image description here
Next, we open the pom.xml file and add the SpringBoot starting dependency
SpringBoot requirements. The project requires Inherit SpringBoot's starting dependency spring-boot-starter-parent

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.4.RELEASE</version>
</parent>

We are doing a simple web engineering development for SpringBoot project, so the project needs to import the startup dependencies of the web.

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

We found that the IDs of these two dependencies both have starter , which means that they are a startup dependency and a collection of dependencies. We will look at it in detail later and wait for Maven to load the dependencies. The pom.xml is as follows :
Insert image description here
If you are using an earlier RELEASE version for the first time, you may get an error when adding dependencies in Maven, for example:

<version>2.0.1.RELEASE</version>

Maven reports an error:
Project 'org.springframework.boot:spring-boot-starter-parent:2.0.1.RELEASE' not found.
The solution is as follows:
Project 'org.springframework.boot:spring-boot-starter-parent:xxxRELEASE' not found


After adding the startup dependencies, we create the SpringBoot boot class, also called the startup class, as follows:

@SpringBootApplication
public class MySpringBootApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(MySpringBootApplication.class);
    }

}

Then create our controller class as follows:

@Controller
public class MyController {
    
    

    @RequestMapping("/mySpringBoot")
    @ResponseBody
    public String quick(){
    
    
        return "springboot 访问成功!";
    }

}

Completed, we start MySpringBootApplication:
Insert image description here
a lot of information is printed on the console, including the spring boot version number, tomcat port number and version number from top to bottom (after introducing the startup dependency of the web project, the embedded tomcat will be started at startup service), as well as the time it takes to start, etc.
Here we try to visit:
Insert image description here
At this point, the creation of the springboot project is completed. It is very simple, and it is much more convenient to develop on it.

3. Use Idea to quickly create a SpringBoot project

First, make sure that when we create the project, we have the Spring startup help option. The old version is called Spring Initializr , and the new version is called Spring Assistant .
Insert image description here

If this option is not available, the solution is as follows:
When IDEA creates a new project, there is no Spring Initializr option


Then we continue to create and do some simple project property settings:
Insert image description here
Then, spring provides a lot of options. When we click in the left frame, the right frame will have more detailed dependency options. When we check a dependency, It will automatically introduce its dependencies for us. Here we check a web development dependency we used above, and then we can also choose the version of spring boot. We choose version 2.3.4: Finally, confirm the name of the project,
Insert image description here
etc. Information, creation completed:
Insert image description here
Creation completed:
Insert image description here
The content in the red box in the picture can be deleted directly. Including the .mvn folder (if you are using maven installed and configured by yourself instead of the maven that comes with idea, please delete it, otherwise it will automatically use the default one to load). Sometimes the maven project created here is not automatically recognized by idea
. (There is no maven window), we need to manually authenticate, select the pom.xml file in the project, right-click, Add as maven project, and then reload the maven project to complete the import of dependencies.
We opened the pom.xml file and found that the configuration we had made before had been imported by default:
Insert image description here
in addition to the above dependencies, there were also boot startup tests and maven plug-ins.
Insert image description here
Our startup boot class has also been created by default, as well as the configuration files we will use later:
Insert image description here
At this point, the creation of the spring boot project has come to an end.

4. Brief analysis of SpringBoot principles and starting dependencies

First of all, in our above example project, two starting dependencies are used, one is for springboot and the other is for web. Let us conduct a simple overview and analysis of these two starting dependencies.

  • spring-boot-starter-parent
    • First, if we hold down alt and click spring-boot-starter-parent, we will enter the pom.xml of spring-boot-starter-parent, which feels like a parent class.
      Insert image description here
    • Here is the pom.xml of spring-boot-starter-parent. We hold down Ctrl again and click spring-boot-starter-dependencies in pom.xml.
      Insert image description here
    • Jump to the pom.xml of spring-boot-starter-dependencies. In the pom.xml of this dependency, there are a lot of dependencies. If you just take a screenshot, there are dozens of dependencies
      Insert image description here
      from the spring-boot above. In the pom.xml of -starter-dependencies, we can find that the version, dependency management, and plug-in management of some coordinates have been defined, so our SpringBoot project already has version locking and other configurations after inheriting spring-boot-starter-parent. Therefore, the role of starting dependencies is to transfer dependencies.

  • spring-boot-starter-web
    • It’s still the same. We hold down Ctrl and click spring-boot-starter-web in pom. , which helps us package a series of web-related dependency packages,
      -
      so we can use springmvc to develop web code without too much configuration at the beginning. Another function of the starting dependency here is to update the versions of each dependency. Automatic configuration is performed, and there will be no problem that some dependencies are unavailable due to version errors between dependencies .

5. Brief analysis of SpringBoot principle and automatic configuration

  • Here we go back and look at the code. Hold down Ctrl and click to view the annotation @SpringBootApplication on the startup class MySpringBootApplication.
    Insert image description here

  • We will find that this annotation is a collection of many annotations, completing the functions of multiple annotations.
    Insert image description here
    Among them,
    @SpringBootConfiguration: is equivalent to the annotation @Configuration, which means that this class is a configuration class of Spring.
    @EnableAutoConfiguration: SpringBoot automatic configuration function is turned on.

  • Hold down Ctrl and click to view the annotation @EnableAutoConfiguration.
    Insert image description here
    Among them, @Import(AutoConfigurationImportSelector.class) imports the AutoConfigurationImportSelector class. From the name, this class is an automatically configured selector class and should be an important implementation part of the automatic configuration function.

  • We continue to hold down Ctrl and click to view the source code of the AutoConfigurationImportSelector
    class . There are many methods in this class. The order we view is:
    1.selectImports(…) to find the imported configuration
    2.getAutoConfigurationEntry(…) to obtain the automatically configured Entry key-value pair
    3. .getCandidateConfigurations(…) Get candidate configurations
    4.List configurations = SpringFactoriesLoader.loadFactoryNames(
    getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
    Here, use factory class loading to obtain configuration.
    The configuration obtained here is the corresponding class in the META-INF/spring.factories file name list

  • Then we find the corresponding spring.factories file in the added dependencies
    Insert image description here

Open it, and the content stored inside is the configuration information about automatic configuration:
Insert image description here

The above configuration file contains a large number of class names ending with Configuration. These classes are classes with automatic configuration information. SpringApplication loads these class names after obtaining them to obtain its configuration information.

  • Let's find a simple configuration class that we are familiar with to briefly take a look at its configuration information. Taking ServletWebServerFactoryAutoConfiguration as an example, we open it. @EnableConfigurationProperties(ServerProperties.class) automatically loads the ServerProperties server configuration property
    Insert image description here
    class. We will Open
    Insert image description here
    Among them, prefix = "server" represents the prefix in the SpringBoot configuration file. SpringBoot will map the attributes starting with server in the configuration file to the fields of this class. The mapping relationship is as follows:
    Insert image description here
    Adding server.port=8888 in the configuration file modifies our http, which is the access port number of tomcat. All properties in the ServerProperties.class class can be configured by themselves. If not configured, Use the concept of convention over configuration and use the agreed default value of 8080.

6.SpringBoot configuration file

SpringBoot is based on convention, so many configurations have default values, but we will modify some configuration values ​​in actual development. We can use application.properties or application.yml , application.yaml to override the configuration.
application.yml and application.yaml are files in the same format, but the simple suffix names are slightly different. There is no essential difference between the two.
SpringBoot will load application.properties or application.yml, application.yaml files from the Resources directory by default . Among them, the application.properties file is a key-value pair type file, which is relatively simple and will not be introduced here. In addition to properties files, SpringBoot can also use yml (yaml) files for configuration. We mainly understand the yml (yaml) files.
Since the content of this configuration file is relatively independent, a separate blog has been opened here. The link is as follows:
[Spring Boot] Configuration File YML: Getting Started and Using

Guess you like

Origin blog.csdn.net/cjl836735455/article/details/109261134