Summary of excerpted knowledge from “SpringBoot Application Development”

Unit 2 SpringBoot Core Configuration

Foreword

SpringBoot follows the concept of “convention over configuration” and uses automatic configuration and customized Java configuration classes to replace the traditional XML configuration method. In actual development, we only need to write very little configuration. This unit is based on the core configuration of a company’s asset management system and introduces SpringBoot’s default configuration files, custom configurations, referencing external configuration files, multi-environment configuration and other related knowledge.

  • Knowledge Objective

  1. Familiar with the two formats of configuration files in SpringBoot
  2. Master the basic annotations of SpringBoot
  3. Learn about custom configurations
  4. Familiar with multi-environment configuration

    1. Default configuration file

1. Spring Boot’s automatic configuration eliminates most manual configuration, but for some specific situations, we still need to customize the configuration and modify the default configuration to adapt to the actual production situation.
In Spring Boot, configuration files have two different formats, namely application.
properties and application.yml (or application.yaml), the configuration files placed in the specified directory will be automatically loaded by Spring Boot, saving us the trouble of manual loading. A common directory for placing configuration files is src/main/resources. (1)application.properties configuration file
When we use Spring Initializer to create a Spring Boot project, an application.properties configuration file will be created by default in the resources directory. You can configure related properties of the project in this file, including system properties, cache, mail, data, transactions, Services and other aspects of configuration. Spring Boot’s configuration properties, default values, descriptions and other information can be viewed in Spring’s official website documentation.
application.properties is a commonly used configuration file with the file extension “properties” and is a text
File, the basic syntax format of the file content is the “key=value” format, with “#” as the beginning of the comment.
If you want to configure the port and context path for Web service access, the basic configuration code is as follows.

The code is as follows (example):

server.port=8081
server.servlet.contest-path=/mytest

(2)application.yml configuration file
In Spring Boot, you can also use YAML format configuration files, which is the officially recommended configuration format.
formula, you can learn more about its detailed introduction through the official website.
First, let’s get to know YAML. YAML is a markup language similar to XML and JSON, emphasizing data-oriented
The center is not focused on markup language, but is essentially a universal data serialization format.
The basic syntax rules of YAML are as follows.
.Case-sensitive, i.e. case-sensitive.
?key: value represents a key-value pair relationship. There must be a space after the colon and before value.
.Use spaces for indentation to indicate hierarchical relationships, and left-aligned data is at the same level.
Tab key indentation is not allowed.
?Use “#” for single-line comments.
If you want to configure the port and context path for Web service access, the configuration code of the YAML format configuration file is as shown in the figure
shown.
The code is as follows (example):

1 server:
  2 port: 8081
    servlet;
3 context-path:/ymltest

There are three main data structures supported in YAML: scalar, object, and array.
Scalar refers to basic, non-divisible values, including integers, floating point numbers, strings, Boolean values, date and time, NULL, etc. There are 3 representations of strings: without quotes, using single quotes, or using double quotes. Generally, the string is written directly without quotation marks. If quotation marks are not used or single quotation marks are used, escape characters (such as “\
“) will be treated as ordinary strings; if double quotation marks are used, escape characters such as “1n” will be processed as newlines. Use different forms to represent strings in YAML format files, and obtain the output results after injecting their values into the Bean.

An object is a collection of key-value pairs, also known as mapping/hash. There are two forms of representation: indented writing and inline writing. If the user object is given a user name and age value, the code using indentation is as follows.

user:
   name: Zhang San
   age:20

If written inline, the code is as follows.

user: {name:Zhang San,age:20}

An array is a set of values arranged in order, also called a sequence/list. If you set a friend relationship for a user object, and the user has two friends, use indentation to write the code as follows.

user:
    name:Zhang San
    age:20
    friends:
        _John Doe
        _王五

Here, a continuation character plus a space is used to represent an item of an array or list, and the space after the continuation character cannot be less. If written inline, the code is as follows.

user:
   name: Zhang San
    age:20
    friends:[李思,王五]

In the YAML format configuration file, each structure can be nested to form a complex structure. If you can continue to use objects in objects, the elements of the array are also arrays. If the user has two friends, and these two friend objects are described, friends corresponds to a list of user objects. The indented code is as follows.

user:
   name:Zhang San
    age:20
 friends:
 -
   name:John Doe
    age:18

 -
   name:王五
     age:20

The two connectors in the code indicate that there are two elements in friends. These two elements are user objects, which are used to set the user name and age values respectively. If written inline, the code is as follows.

user:
   name: Zhang San
    age:20
    friends:[{name:李思,age:18},{name:王五,age:20}]

[] in the code represents a list, {} is used to describe the key-value table. There are two user objects in friends, and commas are used to separate the data of the two user objects.

2. Inject configuration file attributes

Spring Boot provides many configurations, and the default configuration automatically scans and reads property values. But usually we need to define the value ourselves in the configuration file and apply the value to the program. For example, injecting the values in the configuration file directly into the entity class is mainly achieved through some annotations. Commonly used annotations include @ConfigurationProperties and @Value. The @ConfigurationProperties annotation generally binds the configuration file to a class.
The variable values in the file are injected into the member variables of the class;

3. Custom configuration class

1. In Spring Boot, the @Configuration annotation is usually used to define a configuration class. Spring Boot will automatically scan and identify configuration classes, thereby replacing the XML configuration files in traditional Spring. @Configuration annotation generally works on classes and interfaces.
After defining a configuration class, you generally need to use the @Bean annotation on the class method to configure the component. The return object of the method is injected into the Spring container (similar to the tag configuration in the XML configuration file), indicating the return of the current method. Value is a Bean. The component name of the Bean uses the method name by default. You can also use the name or value attribute of the @Bean annotation to customize the name of the component.
In fact, the bottom layer of the @Configuration annotation is the @Component annotation, but the @Configuration annotation focuses on configuration, and the @Component annotation focuses on components. No matter what the focus is, both themselves are Bean objects managed by a loC container.

2. In actual applications, all configurations will not be written in the default configuration file. Users can define their own configuration files. If you want to reference a custom configuration file, you can use the @PropertySource annotation to specify the location and name of the custom configuration file. The @PropertySource annotation does not support reading by default.
configuration file
YAML configuration file. You can use the annotations @Value and @ConfigurationProperties annotations to obtain the
Configure values and inject them into properties of the class.

4. Reference external configuration files

In actual development, it is recommended to use external configuration files when the project is actually launched and deployed. For the loading sequence of external configuration files, please refer to the official website description. Here is a brief introduction to the commonly used external configuration file loading methods. You can use an external JAR package to read the specified configuration file, and change the default configuration file location through the value of spring.config.location.
To reference external configuration files in the project, the basic steps are as follows.
①Create the configuration file app.properties in the config directory of the D drive. Which sets the port and context path
The code for the path is as follows.

server.port=8081
server.servlet.context-path=/outer

②Package the unit2-1 project into a JAR package, and copy the JAR package under target to the D drive.
③Open the command prompt window, switch to the D drive, and execute the following command.

java -jar unit2-1.0.jar
-spring.config.location=d:/config/app.properties

5. Multiple environment configuration

In actual development, a set of applications may be installed and applied to several different environments, such as development environment (dev), test environment (test), production environment (prod), etc. The server port and database of each environment Configurations such as addresses will be different. So to run applications in different environments, do I need to modify the configuration files and copy different installation packages? With only simple configuration in Spring Boot, applications can run in different environments.
Multi-environment configuration is generally divided into the following two steps. ①Define multiple environment configuration files. ②Specify the specific operating environment.
To define multiple environment configuration files in Spring Boot, the configuration file name must meet application-{profile}.yml
format, where {profile} corresponds to the environment identifier, as detailed below.
application-dev.yml: development environment application-test.yml: test environment. application-prod.yml: production environment
You can also use multi-document partitioning to define multiple environment configuration files. Define a configuration file and use documents to configure multiple environments.
separated by the delimiter “-“.
To use one of these environments, you can configure it in the configuration file application.yml
spring.profiles.active attribute, its value corresponds to the S{profle} value, the code is as follows.

spring:
profiles:
active: dev

This tells Spring Boot to load the development environment configuration at startup. If you do not want to fix the environment configuration in the project, you can also determine the environment configuration by passing in the environment parameters when the project is packaged or run. For example, java-jar unit2-1.0.jar –spring.profiles.actvie=dev, it will be more flexible and convenient to distinguish through the packaging startup command.

Summary

The above is what I will talk about today. This article only briefly introduces the use of SpringBoot core configuration.

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Cloud native entry-level skills treeHomepageOverview 16,895 people are learning the system