Interviewer: what is YAML? What does it have to do with Spring Boot?

1. What is YAML

YAML is a recursive abbreviation for "YAML Ain't a Markup Language". YAML actually means "Yet Another Markup Language". The main strength of this voice is data-centric, not markup language. For example, xml language will use a lot of markup.

YAML is a highly readable and easy to understand format used to express data serialization. Its syntax is similar to other high-level languages, and it can simply express data forms such as list (array), hash table, scalar and so on. It uses white space indentation and a large number of appearance dependent features. It is especially suitable for expressing or editing data structures, various configuration files, etc.

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

I won't introduce the basics of Spring Boot. I recommend this practical tutorial:
https://github.com/javastacks/spring-boot-best-practice

2. Basic grammar

  • YAML uses printable Unicode characters and can use UTF-8 or UTF-16.
  • The data structure is in the form of key value pairs, that is, key name: value. Note that there should be a space after the colon.
  • Each list (array) member is represented in a single line and starts with a short bar + blank (-). Or use square brackets ([]) and separate members with commas + whitespace (,).
  • The members of each hash table separate the key value and content with colon + blank (:). Or use braces ({}) separated by commas + whitespace (,).
  • String values generally do not use quotation marks. They can be used if necessary. When double quotation marks are used to represent a string, special characters in the string will be escaped (for example, \ n). Special characters in strings are not escaped when single quotes are used.
  • Case sensitive
  • Indents are used to indicate hierarchical relationships. Indents do not allow tabs, but only spaces, because tabs may have different lengths in different systems
  • The number of indented spaces can be any, as long as the elements of the same level are aligned to the left
  • In a single file, three consecutive hyphens (-) can be used to distinguish multiple files. There are also optional three consecutive periods (...) to indicate the end of the file.
  • '#' represents a comment, which can appear anywhere in a line, single line comment
  • When using commas and colons, they must be followed by a blank character, so you can freely add separators in strings or numeric values (for example, 5280 or 5280) http://www.wikipedia.org )You don't need quotation marks.

3. Data type

  • scalars: single, non separable values
  • Object: a collection of key value pairs, also known as mapping / hashes / dictionary
  • Array: a set of values arranged in order, also known as sequence / list

scalar

Scalars are the most basic data types and non separable values. They are generally used to represent a single variable. There are seven types:

  • character string
  • Boolean value
  • integer
  • Floating point number
  • Null
  • time
  • date
# character 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
float.value1: 314159e-5 # Scientific counting method
# Null, ~ stands for null
null.value: ~
# Time, time in ISO 8601 format, T connection between time and date, and + for time zone
datetime.value: !!timestamp 2021-04-13T10:31:00+08:00
# Date, the date must be in ISO 8601 format, i.e. yyyy mm DD
date.value: !!timestamp 2021-04-13

In this way, we can introduce in the program, as follows:

@RestController
@RequestMapping("demo")
public class PropConfig {

    @Value("${string.value}")
    private String stringValue;

    @Value("${boolean.value}")
    private boolean booleanValue;

    @Value("${boolean.value1}")
    private boolean booleanValue1;

    @Value("${int.value}")
    private int intValue;

    @Value("${int.value1}")
    private int intValue1;

    @Value("${float.value}")
    private float floatValue;

    @Value("${float.value1}")
    private float floatValue1;

    @Value("${null.value}")
    private String nullValue;

    @Value("${datetime.value}")
    private Date datetimeValue;

    @Value("${date.value}")
    private Date datevalue;
}

I won't introduce the basics of Spring Boot. I recommend this practical tutorial:
https://github.com/javastacks/spring-boot-best-practice

object

We know that a single variable can use key value pairs and use colon structure to represent key: value. Note that a space should be added after the colon. You can use key value pairs at the indent level to represent an object, as follows:

person:
  name: dried tangerine peel
  age: 18
  man: true

Then assign these attributes to the Person object in the program. Note that the Person class should add the get/set method, otherwise the attribute will not get the value of the configuration file correctly. Using @ ConfigurationProperties to inject objects, @ value cannot resolve complex objects well.

@Configuration
@ConfigurationProperties(prefix = "my.person")
@Getter
@Setter
public class Person {
    private String name;
    private int age;
    private boolean man;
}

Of course, you can also use the form of key:{key1: value1, key2: value2,...}, as follows:

person: {name: dried tangerine peel, age: 18, man: true}

array

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

person:
  name: dried tangerine peel
  age: 18
  man: true
  address:
    - Shenzhen
    - Beijing
    - Guangzhou

Brackets can also be used for inline display as follows:

person:
  name: dried tangerine peel
  age: 18
  man: true
  address: [Shenzhen, Beijing, Guangzhou]

The introduction method in the code is as follows:

@Configuration
@ConfigurationProperties(prefix = "person")
@Getter
@Setter
@ToString
public class Person {
    private String name;
    private int age;
    private boolean man;
    private List<String> address;
}

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

person:
  name: dried tangerine peel
  age: 18
  man: true
  address: [Shenzhen, Beijing, Guangzhou]
  twoArr:
    -
      - 2
      - 3
      - 1
    -
      - 10
      - 12
      - 30
@Configuration
@ConfigurationProperties(prefix = "person")
@Getter
@Setter
@ToString
public class Person {
    private String name;
    private int age;
    private boolean man;java
    private List<String> address;
    private List<List<Integer>> twoArr;
}

If the array member is an object, it can be in the following two forms:

childs:
  -
    name: Xiao Hong
    age: 10
  -
    name: Xiao Wang
    age: 15
childs: [{name: Xiao Hong, age: 10}, {name: Xiao Wang, age: 15}]

4. Text block

If you want to introduce a multi line text block, you can use the | symbol. Note that there should be a space between the colon: and |.

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

It has the same effect as double quotation marks. Double quotation marks can escape special characters:

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

5. Displays the specified type

Sometimes we need to display the type of specified value, which can be used! (exclamation mark) specifies the type explicitly.! Single exclamation point is usually a custom type,!! Double exclamation marks are built-in types, such as:

# Specify as string
string.value: !!str HelloWorld!
# !! timestamp is specified as the date time type
datetime.value: !!timestamp 2021-04-13T02:31:00+08:00

The types of built-in are as follows:

  • !! int: integer type
  • !! float: floating point type
  • !! bool: Boolean type
  • !! str: string type
  • !! Binary: binary type
  • !! timestamp: date time type
  • !! Null: null value
  • !! Set: set type
  • !! omap,!! pairs: key value list or object list
  • !! seq: sequence
  • !! map: hash table type

6. Quote

The reference will use & anchor point and asterisk symbol, & to establish the anchor point, < < to merge into the current data and reference the anchor point.

xiaohong: &xiaohong
  name: Xiao Hong
  age: 20

dept:
  id: D15D8E4F6D68A4E88E
  <<: *xiaohong

The above is finally equivalent to the following:

xiaohong:
  name: Xiao Hong
  age: 20

dept:
  id: D15D8E4F6D68A4E88E
  name: Xiao Hong
  age: 20

There is also an intra file reference, which refers to the defined variables, as follows:

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

7. Single file multi configuration

Multiple document partitions, that is, multiple configurations, can be implemented in the same file. In a yml file, separate multiple different configurations by - and decide which configuration to enable according to the value of spring.profiles.active

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


#Development environment configuration
spring:
  profiles: dev # The profiles property represents the name of the configuration
server:
  port: 8080


#Production environment configuration
spring:
  profiles: pro
server:
  port: 8081

Source: blog.csdn.net/chenlixiao007

Recent hot article recommendations:

1.1000 + Java interview questions and answers (2021 latest version)

2.Stop playing if/ else on the full screen. Try the strategy mode. It's really fragrant!!

3.what the fuck! What is the new syntax of xx ≠ null in Java?

4.Spring Boot 2.6 was officially released, a wave of new features..

5.Java development manual (Songshan version) is the latest release. Download it quickly!

Feel good, don't forget to like + forward!

Posted by nvee on Mon, 29 Nov 2021 07:38:48 -0800