Location>code7788 >text

II. Spring Boot in the "dependency management and auto-configuration" detailed through to the end (with + detailed code flow)

Popularity:300 ℃/2024-08-29 22:55:00

II. Spring Boot in the "dependency management and auto-configuration" detailed through to the end (with + detailed code flow)

@

catalogs
  • II. Spring Boot in the "dependency management and auto-configuration" detailed through to the end (with + detailed code flow)
  • 1. How to understand "agreement over configuration"
  • 2. Spring Boot dependency management and auto-configuration
    • 2.1 Spring Boot Dependency Management
      • 2.1.1 What is Dependency Management
      • 2.1.2 Modify Auto-Arbitration/Default Version Number
    • 3.1 starter Scene starter
      • 3.1.1 Description of the starter scene starter
      • 3.1.2 Spring Boot's official starter scene starter
      • 3.1.3 Third-party starter scene starters supported by Spring Boot
    • 4.1 Spring Boot Autoconfiguration
      • 4.1.1 What are Spring Boot autoconfigurations?
      • 4.1.2 How to Change the Default Configuration in Spring Boot
    • 5.1 How to change the default configuration
      • 5.1.1 How to modify the default scan packet structure
      • 5.1.2 Resources (under the class path)\ Configuration in Spring Boot
      • 5.1.3 Demonstration: Using some common configurations
      • 5.1.4 Custom Configuration in Spring Boot
    • 6.1 Where to Configure Read Profiles in Spring Boot
    • 7.1 Automatic configuration, observing the principle of loading on demand
  • 3. Summary:
  • 4. Finally:


1. How to understand "agreement over configuration"

Convention over Configuration (CoC), also known as Conventional Programming, is a software design specification that is essentially a specification for something in a system, library or framework.

A popular and reasonable default (default value)
2. For example, if there is a class named User in the model, then there will be a table named user in the database, and only deviations from this convention need to be configured (e.g.
(You want to name the table: t_user, etc. You only need to write configuration about this name if you are not a user)
3. Simply put, if all youExpected Configuration together withConfiguration of the agreement consistent, then no configuration can be done, and replacement configuration of the convention is only required when the convention does not meet expectations.
4. Convention over configuration: why a "convention over configuration"?
A convention is really a norm, and when the norm is followed, then there exists generality. Generality exists, and then things becomerelatively simple , the cost of communication between programmers will be reduced, productivity will increase, and collaboration will become easier.
5. In life, there are a lot of situations like this: for example, if two people, both boys, say they are going to the bathroom together, then both of them (by default, the agreement is to go to the boys' restroom, and it is specifically stated that it is to go to the girls' restroom).
6. Note: Misunderstanding: The default is to use the convention, but if you configure it, it still uses the information you configured.

2. Spring Boot dependency management and auto-configuration

2.1 Spring Boot Dependency Management

2.1.1 What is Dependency Management

  1. spring-boot-starter-parent There is also the parent project, which declares the version numbers of common dependencies used in development

  2. in additionAutomatic version arbitration If the programmer doesn't specify a dependencyjar version, the version specified by the parent project takes precedence.

在这里插入图片描述

在这里插入图片描述

2.1.2 Modify Auto-Arbitration/Default Version Number

If Spring Boot is configured by default with thejar Dependent version, no, what we want how to configure the change to what we want.

How to modify the corresponding jar in Spring Boot.

Demo: Modify the SpringBoot mysql driver to version 5.1.49.

First, let's first learn how to view the data that corresponds to our desiredjar What version of Spring Boot is used in the default configuration.

In spring-boot-dependencies\2.5.3\spring-boot-dependencies-2.5., we can find the correspondingjar package dependencies, as shown in the following figure: Here, Spring Boot's default configuration for MySQL dependencies is8.0.26 (used form a nominal expression)

在这里插入图片描述

Check the key that specifies which version you are currently relying on.

在这里插入图片描述

在这里插入图片描述

There are two ways to modify the corresponding jar in Spring Boot:

  • Way one: Directly in the project's Import the file directly into the file you want.jar version is sufficient.
  • Way two: is the same as Mode 1, the difference is the way it is written, which is different: "Mode 2: is to put thejar information andVersion of jar The information is written separately now."

Way one: Modify Rewrite Configuration When Maven is updated, it depends on the new , mysql driver.

Directly import the dependencies we want.jar configuration, and then, update Maven.

在这里插入图片描述

  <! -- Custom settings: 1 We specify the mysql/driver version ourselves -- >
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version> <! --Unspecified is, using the SpringBoot convention (i.e., the default 8.26)-->
        </dependency>

Then, after we refresh Maven and reload thejar

在这里插入图片描述

Attention: If the configured dependenciesjar If you don't specify the version of the package, the SpringBoot agreed upon version (i.e., the default 8.26) will be used.

As follows: we comment out the version of the indicated version, update it again, and see.

在这里插入图片描述

complete Information.

<?xml version="1.0" encoding="UTF-8"? >;xml version="1.0" encoding="UTF-8"?
<project xmlns="/POM/4.0.0"
         xmlns:xsi="http:///2001/XMLSchema-instance"
         xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0." >
    <modelVersion>4.0.0</modelVersion>

    <groupId></groupId>
    <artifactId>quickstartBlog</artifactId>
    <version>1.0-SNAPSHOT</version>


    <! -- Importing springboot parent project, prescribed writeup -- >
    <parent>
        <groupId> </groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
    </parent>


    <! -- Import web project scenario launcher, will automatically import and web development related dependencies, very convenient -- > < /parent> < /parent> < /parent> <!
    <dependencies>.
        <dependencies>.
            <groupId> </groupId>.
            <artifactId>spring-boot-starter-web</artifactId>.
        </dependency>.

        <! -- Customization: 1 We specify the mysql/driver version ourselves -- >
        <dependency>
            <groupId> mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version> <! --Unspecified is, using the SpringBoot convention (i.e., the default 8.26)-->
        </dependency>.
    </dependencies>




</project>

Way two: will depend onjar The configuration information for the package is written separately from the configuration version.

  • exist <properties> tag, configure the jar'sversion information The version information of several different jars can be configured.

  • exist <dependencies> tag, configure the jar'sConfigure coordinate information If you want to configure more than one jar, you can do so.

在这里插入图片描述

    <properties>
        <>5.1.49</>
    </properties>


    <! -- Import web project scenario launcher, will automatically import and web development related dependencies, very convenient --> <
    <dependencies>.
        <! -- Customization: 1 We specify the mysql/driver version --> <dependencies> <!
        <dependency>
            <groupId> mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

Update Maven to reload the jar.

在这里插入图片描述

complete Information.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="/POM/4.0.0"
         xmlns:xsi="http:///2001/XMLSchema-instance"
         xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.">
    <modelVersion>4.0.0</modelVersion>

    <groupId></groupId>
    <artifactId>quickstartBlog</artifactId>
    <version>1.0-SNAPSHOT</version>


    <!-- import (data) springboot parent project,Prescribed wording -->
    <parent>
        <groupId></groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
    </parent>


    <properties>
        <>5.1.49</>
    </properties>


    <!-- import (data) web Project Scene Launcher,会自动import (data)和 web Development-related dependencies,very convenient -->
    <dependencies>
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Customized settings:1 We specify ourselvesmysql/Driver version-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>




</project>

3.1 starter Scene starter

3.1.1 Description of the starter scene starter

In development, we introduce a starter for the scenario in question, and all the relevant dependencies for that scenario are introduced, e.g., the web development we learned about earlier is introduced, and the starter will import all the packages related to web development.

在这里插入图片描述

在这里插入图片描述

dependency tree : You can see that spring-boot-starter-web introduces spring-web mvc, spring-web development module, spring-boot-starter-tomcat scenario, spring-boot-starter-json scenario, and a whole bunch of related packages. These scenarios introduce a large number of related packages , these dependencies can quickly start and run a project to improve development efficiency .

在这里插入图片描述

在这里插入图片描述

The most basic dependency of all scene starters is thespring-boot-starter , as can be seen from the previous dependency tree analysis.

在这里插入图片描述
在这里插入图片描述

This dependency is also the core dependency that SpringBoot automatically configures

在这里插入图片描述

3.1.2 Spring Boot's official starter scene starter

Spring Boot's official starter scene starter introduction:/spring-boot/reference/using/#

在这里插入图片描述

That means: we often use spring-boot-starter-xxx in development, such as spring-boot-starter-web, the scene is used for web development, that is to say, xxx is some kind of development scenario.

At this point, we just introduce the starter, and all the usual dependencies for this scenario are automatically introduced.

All scenarios supported by Spring Boot3 are as follows: official address:/spring-boot/reference/using/#

在这里插入图片描述

3.1.3 Third-party starter scene starters supported by Spring Boot

Spring Boot also supports third-party starters.

Third-party starters should not start with spring-boot, as this is the official naming convention reserved for spring-boot.
Third-party bootstrap projects usually start with a project name, e.g., a third-party bootstrap project with the name "XXX" is usually named "XXX-spring-boot-stater".

That is to say: xxx-spring-boot-starter is a third-party scenario starter that simplifies development for us

4.1 Spring Boot Autoconfiguration

Do we remember that when we learned SSM integration earlier, we needed to configure Tomcat, configure Spring MVC, and configure how to scan packages, configure character filters, configure view parsers, file uploads, etc. ✏️✏️✏️SSM Integration (Spring + MyBatis; Spring + Spring MVC) - CSDN Blogs It's very troublesome. It's a pain in the ass. In Spring Boot, on the other hand, there areauto-configuration Mechanisms to improve development efficiency.

Briefly review the configuration of previous SSM integrations:

在这里插入图片描述

在这里插入图片描述

4.1.1 What are Spring Boot autoconfigurations?

  1. Auto-Configuration of Tomcat

在这里插入图片描述

  1. Spring MVC is automatically configured

在这里插入图片描述

  1. Common Web features are automatically configured: for example, character filters.

We can verify this by getting the ioc container and looking at the components created by the container.

在这里插入图片描述

package ;


import ;
import ;
import ;


// @SpringBootApplication Indicates that it is a springboot appliance
@SpringBootApplication
public class MainApp {
    public static void main(String[] args) {
        // activate (a plan) SpringBoot appliance程序
        ConfigurableApplicationContext ioc = (, args);

        // Viewing components inside a container
        String[] beanDefinitionNames = ();
        for (String beanDefinitionName : beanDefinitionNames) {
            ("beanDefinitionName ---" + beanDefinitionName);
        }


    }
}

在这里插入图片描述

A more direct way of looking at it: we can debug the ioc to see which bean objects have been created in the ioc container by hitting a breakpoint in the ioc.

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

In Spring Boot's auto-configuration, we don't need to configure thescanning packet Spring Boot has a default scanning package structure.

The following is from the official Spring Boot documentation/spring-boot/reference/using/#-the-default-package]: the automatically scanned package structure. If you develop your project according to this "convention/autoscan package structure", you don't need to configure the scanning package. The Spring Boot convention/default will do.

在这里插入图片描述

com
 +- example
     +- myapplication
         +- 
         |
         +- customer
         |   +- 
         |   +- 
         |   +- 
         |   +- 
         |
         +- order
             +- 
             +- 
             +- 
             +- 

在这里插入图片描述

4.1.2 How to Change the Default Configuration in Spring Boot

Demo: What should I do with the request to scan under the package?

Let's start by testing the main program class, which is not created according to the Spring Boot default package structure. What happens.

In quickstartBlog\src\main\java\com\rainbowsea\directory/package, create a class named main program. And test, this is not accessible.

在这里插入图片描述

Run the main program, open a browser and type:http://localhost:8080/hi Testing.

在这里插入图片描述

The reason is: hello configuration of HelloController is in Spring Boot's default auto-configuration of the package structure, and our hi configuration of HiController is not in Spring Boot's auto-configuration of the package structure, and we have not configured the package scanning, Spring Boot naturally can not be found! Spring Boot can't find it.

在这里插入图片描述

5.1 How to change the default configuration

5.1.1 How to modify the default scan packet structure

As we tested above, the package under the package can not be scanned, can not be scanned, can not be added to the ioc container by Spring Boot management up, can not be accessed.

So wanting to, so that it can be scanned solves this, inaccessible can't be found problem.

Methods:

We modify , add scanning packages .

utilization@SpringBootApplication in thescanBasePackages annotation attribute, the value of this attribute: is to let Spring Boot scan, the package path.

在这里插入图片描述

在这里插入图片描述

package ;


import ;
import ;
import ;


// @SpringBootApplication Indicates that it is a springboot appliance
// directly in the SpringBootApplication annotation followed by the,have sb do sth Spring Boot The path of the packages to be scanned into
 @SpringBootApplication(scanBasePackages = {""})
public class MainApp {
    public static void main(String[] args) {
        // activate (a plan) SpringBoot appliance程序
        ConfigurableApplicationContext ioc = (, args);

        // Viewing components inside a container
        String[] beanDefinitionNames = ();
        for (String beanDefinitionName : beanDefinitionNames) {
            ("beanDefinitionName ---" + beanDefinitionName);
        }


    }
}

Once configured, let's reboot again and try running it.

在这里插入图片描述

5.1.2 Resources (under the class path)\ Configuration in Spring Boot

The most important and central configuration file of the SpringBoot project is the one in which all the framework configurations can be described:Configuration files in the Spring Boot framework When all the configurations in the book - CSDN Blogs

5.1.3 Demonstration: Using some common configurations

In Spring Boot, there are default configurations, and if you want to change the configuration, you can change it in the resources\ file. As for the The file is something we need to create manually.

Special note: The filename must beThe suffix should not be changed. It is strongly recommended to put it under the root path of the class (that is, theresources Catalog )

Secondly, note that in.properties Suffixed configuration files, among other things, are written without spaces, as much as possible.

Below:

  • Demo 1: We set up the server Tomcat, the port on which our project will start, the default is 8080, here we set it to 9090.

在这里插入图片描述

Write Configuration: Setting the Listening Window for Modifying Server to 9090

# modificationsserverThe listening window for the 9090
# Tomcat started on port(s): 9090 (http) with context path ''
=9090

在这里插入图片描述

After writing the configuration, run the main program, reload the program and see.

在这里插入图片描述

在这里插入图片描述

  • Demo 2: Modify the size of the file upload;

在这里插入图片描述

# Modify the server's listening window to 9090.
# Tomcat started on port(s): 9090 (http) with context path ''
=9090


# Modify the file upload size
# Interpret where this configuration is read!
#-The -file-size attribute specifies the size limit of the file that SpringBoot uploads (which means "convention is better than configuration").
# By default, liar-hi is always mapped to a class, e.g.: -file-size
# Default liar's hi is always mapped to a class, e.g.: -file-size
# Place the cursor on the property, type ctrl + b, or hold down ctrl + click, you can locate which class (property) the property is managed to.
-file-size=10MB

Here, if we want to see the effect, we need to Debug, hit a breakpoint and Debug to see the effect more clearly.

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

  • Demo Three: Configure the mapped path to the starting project root .

在这里插入图片描述

# Modify the server's listening window to 9090.
# Tomcat started on port(s): 9090 (http) with context path ''
=9090


# Modify the file upload size
# Interpret where this configuration is read!
#-The -file-size attribute specifies the size limit of a file that SpringBoot can upload (which means "convention is better than configuration").
# By default, liar-hi is always mapped to a class, e.g.: -file-size
# Default liar's hi is always mapped to a class, e.g.: -file-size
# Place the cursor on the property, type ctrl + b, or hold down ctrl + click, you can locate which class (property) the property is managed to.
-file-size=10MB




# Configure the mapped path to the starting project root
-path=/rainbowsea

Restart the program and test:

在这里插入图片描述

Special Note: Explanation

Where is the above configuration file read from?

For example, the -file-size attribute specifies a limit on the size of files that can be uploaded by SpringBoot (reflecting "convention over configuration").

By default Spring Boot maps to a class, e.g. -file-size, which maps/associates to the MultipartProperties class. Configurations are mapped to the corresponding class.

And by placing the cursor over the property and typing ctrl + b, or by holding down ctrl + clicking, we can locate the class (attribute) to which the property is managed.

在这里插入图片描述

5.1.4 Custom Configuration in Spring Boot

In Spring Boot, we can also also also add the.properties file to customize the configuration via the@Value("${}") way to get the value of the corresponding attribute.

在这里插入图片描述

# Modify the server's listening window to 9090.
# Tomcat started on port(s): 9090 (http) with context path ''
=9090


# Modify the file upload size
# Interpret where this configuration is read!
#-The -file-size attribute specifies the size limit of a file that SpringBoot can upload (which means "convention is better than configuration").
# By default, liar-hi is always mapped to a class, e.g.: -file-size
# Default liar's hi is always mapped to a class, e.g.: -file-size
# Place the cursor on the property, type ctrl + b, or hold down ctrl + click, you can locate which class (property) the property is managed to.
-file-size=10MB




# Configure the mapped path to the starting project root
-path=/rainbowsea


# Customize configuration properties
=

在这里插入图片描述

package ;


import ;
import ;
import ;
import ;

@Controller // Inject into the ioc container.
public class HiController {
    @RequestMapping("/hi") // Set the request mapping path.
    @ResponseBody // Indicates that the return is a json/string, not a web page.
    public String hi(){
        ("website" + website); }
        return "hi~, spring boot";
    }

    // Requirements for website, attribute value from k-v
    @Value("${}")
    private String website; }
}

Run the test:

在这里插入图片描述

Of course, we can also configure it to a bean object, but there is a better way to configure it to a bean object, using Spring Boot's container management.

6.1 Where to Configure Read Profiles in Spring Boot

Open , and look at the source code;

在这里插入图片描述

在这里插入图片描述

// Specify: where the location can be stored so that Spring Boot can successfully read it.
private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:. /,file:. /config/*/,file:. /config/";

// Specify: Configuration class, if it is: application.
private static final String DEFAULT_NAMES = "application"; // Specify: Configuration class to be: application.

7.1 Automatic configuration, observing the principle of loading on demand

Autoconfiguration adheres to the load-on-demand principle: that is, which scenario is introducedstarter The jar associated with the scene will be loaded; starters that are not introduced will not have their associated jar loaded.

在这里插入图片描述

All of SpringBoot's autoconfiguration features are inside the spring-boot-autoconfigure package;

在这里插入图片描述

The autoconfiguration package in Spring Boot generally corresponds to , as shown in Figure

在这里插入图片描述


3. Summary:

  1. Spring Boot understands among other things that "convention over configuration", also known as convention programming, is a software design specification, essentially for something in a system, class library or framework. Reduce unnecessary configuration and use conventions (default configuration)?
  2. Viewing the version of the jar in Spring Boot, and modifying the version of the jar in Spring Boot for bytes.
    1. Way one: Directly in the project's Import the file directly into the file you want.jar version is sufficient.
    2. Way two: is the same as Mode 1, the difference is the way it is written, which is different: "Mode 2: is to put thejar information andVersion of jar The information is written separately now."
  3. Spring Boot when the starter scene starter, Spring Boot official starter scene starter description:/spring-boot/reference/using/#
  4. Spring Boot autoconfiguration, Spring Boot default scan package structure, modify the configuration scan package
  5. Core configuration files in Spring Boot understanding and use. Each of these configuration properties corresponds to a property of a class in Spring Boot and is added to the ioc container.
  6. The autoconfiguration packages in Spring Boot generally correspond to the

4. Finally:

"In this final chapter, I would like to express my gratitude to each and every one of my readers. Your attention and responses have been a source of motivation for me to create, and I have drawn endless inspiration and courage from you. I will keep your encouragement in my heart and continue to struggle in other areas. Thanks to you all, we will always meet again at some point."

在这里插入图片描述