“This is the ninth day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”

Spring Boot 2. X restful Web application

Based on the above code changes

  • Spring Boot allows you to configure different profiles in a single configuration file

  • Spring Boot defaults to default when no Profile is specified

  • Spring Boot provides the @ConfigurationProperties annotation, which makes it easy to load a piece of configuration into a Bean

  • IO /spring-boot…

Source address: github.com/langyastudi…

Reading a configuration file

Configuration of the sample

You use an application.yml yml profile instead of an application.properties ini profile.

langyastudio:
  disk:
    local:
      root: /mnt/volume/edu/pms/
      # Only works when Windows is running
      #use for test on windows OS
      win-root: Z:/volume/edu/pms/
      File storage path
      root-file: ${langyastudio.disk.local.root}file/
      The transcoding path is automatically mapped to MTS /
      root-mts: ${langyastudio.disk.local.root}mts/
      # Temporary path for file storage
      root-tmp: ${langyastudio.disk.local.root}temp/upload/
      #- Images - Direct viewable file size 10M
      browse-img-max-size: 10485760
      #- Image - transcodeable file size 20M
      cvt-img-max-size: 20971520
      # Maximum file size, default is 10M
      max-size: 10485760
      # Allow empty files:
      allow-empty: false
      # Allowed file types:
      allow-types: jpg, png, gif
Copy the code

@Value

The @value annotation can be used to read the configuration file. For example, if you need to get the root configuration item in a class, you can inject @value:

@RestController
@RequestMapping("/config")
public class ConfigController
{
    @Value("${langyastudio.disk.local.root}")
    String root;
    
    @Value("${langyastudio.disk.local.root:/mnt/volume/edu/pms/}")String root; . }Copy the code

This demonstrates the injection of configuration items in the Control layer. Injecting configuration items into other class files requires the use of @Component

Can use ${langyastudio. Disk. Local. Root: / MNT/volume/edu/PMS /} to set the default values

@ ConfigurationProperties

Define the Bean

For better configuration management, Spring Boot allows you to create a Bean that directly injects a set of configuration items. To define a Java Bean, ensure that the property name of the Java Bean is the same as the configuration:

@Data
@ConfigurationProperties(prefix = "langyastudio.disk.local")
public class DiskLocalConfig
{
    private String       root;
    private String       winRoot;
    private String       rootFile;
    private String       rootMts;
    private String       rootTmp;
    private Integer      browseImgMaxSize;
    private Integer      cvtImgMaxSize;
    private Integer      maxSize;
    private Boolean      allowEmpty;
    private List<String> allowTypes;
}
Copy the code

Note that @ConfigurationProperties(prefix = “Langyastudio.disk.local “) indicates that all child configurations of the item will be read from the configuration item langyastudio.disk.local and mapped to the property field one by one.

Define ConfigurationPropertiesScan

Represents a property scan of those class files to assemble them into beans. Com.langyastudio.springboot.com mon. * said location.

@ConfigurationPropertiesScan("com.langyastudio.springboot.common.*")
@Configuration
public class WebConfig implements WebMvcConfigurer
{}Copy the code

You can also use @configuration instead

Using configuration Items

@AutowiredDiskLocalConfig diskLocalConfig; ---- Actual data {"root": "/mnt/volume/edu/pms/"."winRoot": "Z:/volume/edu/pms/"."rootFile": "/mnt/volume/edu/pms/file/"."rootMts": "/mnt/volume/edu/pms/mts/"."rootTmp": "/mnt/volume/edu/pms/temp/upload/"."browseImgMaxSize": 10485760."cvtImgMaxSize": 20971520."maxSize": 10485760."allowEmpty": false."allowTypes": [
        "jpg"."png"."gif"]}Copy the code

That way, you can use configuration items in a way that doesn’t require a bunch of @ values

Configuring environment Profiles

How to use different configurations in different environments such as R&D, test, and launch? Profiles enable a set of code to enable different configurations and functions in different environments.

We can have three configuration files:

  • application.yml
  • application-dev.yml
  • application-pro.yml

Yml or application-pro.yml will automatically overwrite the existing configuration items in the application-.

When the Java program is running, you can specify which profile to use by –spring.profiles. Active =dev. To start with a dev environment, enter the following command:

$ java -Dspring.profiles.active=dev -jar xxx.jar
Copy the code

Of course, if you use only one configuration file, you can achieve multiple document partitions, that is, the same multi-configuration function. In a YML file, separate multiple different configurations by — and decide which configuration to enable based on the value of spring.profiles.active.

You can use @profile to specify different groups of configuration items to achieve the same effect. I won’t go into details here

# Public configuration
spring:
  profiles:
    # Specifies which document block to use
    active: pro
---
spring:
  profiles: dev

server:
  port: 8080
---
spring:
  profiles: pro

server:
  port: 8081
Copy the code

Yml file details

The following content is from the network, the specific reference link could not be found

What is a YAML

YAML is a recursive abbreviation of “YAML Ain’t a Markup Language”. YAML really means: “Yet Another Markup Language” (still a Markup Language). This is data-centric speech rather than markup speech, as languages like XML use a lot of markup.

YAML is a readable, easy-to-understand format for expressing data serialization. Its syntax is similar to that of other high-level languages, and it is easy to express lists (arrays), hash tables, scalars, and other data forms. It uses white space indentation and a heavy dependency on appearance, making it particularly suitable for expressing or editing data structures, various configuration files, and so on.

The YAML configuration file suffix is.yml. For example, the configuration file application.yml used in the Springboot project.

The basic grammar

  • YAML uses printable Unicode characters, which can be used in UTF-8 or UTF-16.
  • The data structure takes the form of a key-value pair, key-name: value, with a space after the colon.
  • Each list (array) member is represented by a single line, starting with a short bar + blank (-). Or use square brackets ([]) and separate members with a comma + whitespace (,).
  • Each hash table member separates the key value and content with a colon + blank (:). Or use curly braces ({}), separated by a comma + whitespace (,).
  • String values are usually not quoted, but can be used if necessary. Special characters in the string (such as \n) are escaped when double quotes are used. Special characters in the string are not escaped when single quotes are used.
  • Case sensitivity
  • Use indentation to indicate hierarchy. Indentation does not allow tabs, only Spaces, because tabs may be different in different systems
  • You can indent as much space as you like, as long as elements of the same level are left aligned
  • Multiple files in a single file can be distinguished by three consecutive hyphens (-). There is also the option of three consecutive dots (…). Used to indicate the end of a file.
  • ‘#’ represents a comment that can appear anywhere on a line, a single line comment
  • Both commas and colons must be followed by a whitespace character, so you can add a delimiter (for example, 5,280 or www.wikipedia.org) to a string or number without using quotation marks.

The data type

  • Scalars: Single, non-divisible values

  • 1. A collection of key-value pairs, also known as mapping/hashes/dictionaries.

  • 1. A group of sorted values, also called a sequence/list.

scalar

Scalars are the most basic type of data, non-divisible values. They are commonly used to represent single variables. There are seven of them:

  • string
  • Boolean value
  • The integer
  • Floating point Numbers
  • Null
  • time
  • The date of
# string
string.value: Hello! I'm tangerine peel!
# Boolean, true or false
boolean.value: true
boolean.value1: false
# integer
int.value: 10
int.value1: 0b1010_0111_0100_1010_1110 # binary
# floating point number
float.value: 3.14159
# Scientific numeration
float.value1: 314159e-5 
# Null, ~ represents Null
null.value: ~
The time is in ISO 8601 format, the time and date are connected by T, and the time zone is represented by +
datetime.value: !!!!! timestamp 2021-04-13T10:31:00+08:00
Date, date must be in ISO 8601 format yyyY-MM-DD
date.value: !!!!! timestamp 2021-04-13
Copy the code

object

We know that a single variable can be a key-value pair, using a colon structure for key: value. Note that the colon must be followed by a space. An object can be represented with an indent hierarchy of key-value pairs, as follows:

person:
  name: Dried tangerine or orange peel
  age: 18
  man: true
Copy the code

An array of

Each element of an array can be composed of a bar with a space-beginning line, as shown in the address field:

person:
  name: Dried tangerine or orange peel
  age: 18
  man: true
  address:
    - shenzhen
    - Beijing
    - Guangzhou
Copy the code

You can also use brackets for inline display, as follows:

person:
  name: Dried tangerine or orange peel
  age: 18
  man: true
  address:
    [shenzhen.Beijing.Guangzhou]
Copy the code

If the members of an array field are also an array, the nested form can be used, as follows:

person:
  name: Dried tangerine or orange peel
  age: 18
  man: true
  address: [shenzhen.Beijing.Guangzhou]
  twoArr:
    -
      - 2
      - 3
      - 1
    -
      - 10
      - 12
      - 30
Copy the code

If the array member is an object, it takes one of two forms:

childs:
  -
    name: The little red
    age: 10
  -
    name: wang
    age: 15
Copy the code

Text block

If you want to introduce more lines of text block, you can use | symbols, pay attention to in the colon, and to have space between the | symbols.

person:
  name: | Hello Java!! I am fine! Thanks! GoodBye!Copy the code

It has the same effect as double quotes, which escape special characters:

person:
  name: "Hello Java!! \nI am fine! \nThanks! GoodBye!"
Copy the code

Display the specified type

Sometimes we need to display the type that specifies some value, can use! (exclamation point) Explicitly specifies the type. ! Single exclamation marks are usually custom!! The double exclamation mark is a built-in type, for example:

# specifies a string
string.value: !!!!! str HelloWorld!
#!!!!! Timestamp specifies a date-time type
datetime.value: !!!!! timestamp 2021-04-13T02:31:00+08:00
Copy the code

The built-in types are:

  • !!!!! Int: indicates an integer
  • !!!!! Float: float type
  • !!!!! Bool: Indicates the Boolean type
  • !!!!! STR: the value is a string
  • !!!!! Binary: Indicates the binary type
  • !!!!! Timestamp: Indicates the date and time type
  • !!!!! Null: an empty value
  • !!!!! Set: indicates the collection type
  • !!!!! Omap,!!!!! Pairs: lists of keys or lists of objects
  • !!!!! Sequence of seq:
  • !!!!! Map: indicates the hash table type

reference

References use the & anchor conformance and asterisk notation, & to establish the anchor, and << to merge into the current data, to reference the anchor.

xiaohong: &xiaohong
  name: The little red
  age: 20

dept:
  id: D15D8E4F6D68A4E88E
  < < : *xiaohong
Copy the code

The above ultimately corresponds to the following:

xiaohong:
  name: The little red
  age: 20

dept:
  id: D15D8E4F6D68A4E88E
  name: The little red
  age: 20
Copy the code

There is also an in-file reference, which refers to a defined variable, such as:

base.host: https://chenpi.com
add.person.url: ${base.host}/person/add
Copy the code