SpringBoot off Series - Profile (c)

A, SpringBoot configuration file

He said play configuration file, we are not familiar long before springboot, we use ssh, ssm framework for the development of every day when in contact with the profile, then basically .properties configuration file and .xml file suffix , basically those are the two formats, and configured we can read data from a configuration file is injected into our program now also supports springboot .properties files, xml with running out, new configuration of a yaml file, which is a new configuration file, we are also possible in the future configuration file will use this type of profile.

Two, YAML Configuration Files Introduction

2.1 What is YAML

YAML is "YAML Is not a Markup Language" (YAML is not a markup language ) is a recursive acronym . In the development of the language, YAML  meant in fact: "Yet Another Markup Language" (still a markup language ), but in order to emphasize the language as a data center, rather than focusing on the markup language, and Abbreviations used reverse renamed. It's structured like markup language, but the grammar and writing formal aspects markup language much worse, while its syntax to write it more able to express more streamlined data content.

2.2 YAML and compare Properites

Compared to the traditional properties profile way, YAML syntax is more strict syntax will be more, let's compare the two ways of writing profiles for the same configuration.

Properties configuration file:

environments.dev.url=http://dev.bar.com
environments.dev.name=Developer Setup
environments.prod.url=http://foo.bar.com
environments.prod.name=My Cool App
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com

YAML configuration file:

environments:
    dev:
        url: http://dev.bar.com
        name: Developer Setup
    prod:
        url: http://foo.bar.com
        name: My Cool App
my:
    servers:
        - dev.bar.com
        - foo.bar.com

As can be seen, YAML configuration file structure more clear (expressed by the hierarchy of spaces to indent), the amount of data written is small, there is a hierarchy and more conducive to resolve the machine.

Three, YAML syntax

3.1 Data Format

First YAML allows data representing three structures, namely, the constant (literal), an object, an array. Data configuration example below:

# Means that the url attribute value; 
url: HTTP: // www.wolfcode.cn 
# server.host i.e., a value indicating the attribute; 
server: 
    Host: HTTP: // www.wolfcode.cn 
# arrays, i.e. server expressed as [a , B, C] 
Server:
     - 120.168.117.21 
    - 120.168.117.22 
    - 120.168.117.23 
# constants 
PI: 3.14 # define a value 3.14 
hasChild would have to: to true   # define a boolean 
name: 'Hello YAML' # define a string

Notes 3.2

Comments begin with #, and Properties in the same YAML, YAML only line comments.

3.3 format requirements

In 1.YAML case-sensitive.

2. Use spaces to indent represent hierarchical relationships, unified indent level belong to the same level.

3. indented with spaces only, can not use tab, limit the number of spaces not only require the same level to maintain the same number of spaces (Tucao look, design YAML people estimated to have this habit).

3.4 Object Format

When we want to mark an object when using key: value of the form, where attention must be a space behind the colon (again Tucao it: do not understand why):

key: value

Object contains a plurality of values:

obj1: 
    key1: value1
    key2: value2

The writing line, the object is written to the word order YAML line, of the form {}, and this almost json:

key: {key1: value1, key2: value2}

Complex object format, may be a key target of multiple values, for example, is an array, where we use a question mark + a space represents a complex key value, a colon + a space represents a value:

?  
    - complexkey1
    - complexkey2
:
    - complexvalue1
    - complexvalue2

Is meant herein, key object is an array [complexkey1, complexkey2], the value is [complexvalue1, complexvalue2].

3.5 Array Format

In YAML, the use of a - and a space represents an array element, the same format and other objects, array elements can also be a target, unlimited nested:

hobby:
    - running
    - reading

Array may comprise a number of object structure:

products:
    -
        id: 1
        name: iphone
        price: 5000
    -
        id: 2
        name: xiaomi
        price: 3000

Arrays can also be written inline style:

products: [{id: 1,name: iphone,price: 5000},{id: 2,name: xiaomi,price: 3000}]

3.6 Constant

YAML structure provides a variety of constants, comprising: integer, floating point, string, NULL, date, boolean, time, etc., can look at the following example:

Boolean: 
     - # TRUE to true , are True
     - # FALSE to false , False can be
 a float :
     - 3.14 
    - 6.8523015e +. 5   # scientific notation may be used
 int :
     - 123 
    - 0b1010_0111_0100_1010_1110 # binary representation
 null : 
    the nodeName: ' Node ' 
    parent : ~ use ~ # represents null
 String :
     - ha
     - ' the Hello World '   # use double or single quotes wrapped special characters
     - NEWLINE 
      NEWLINE2 # string can be split into a plurality of rows, each row is converted into a space
DATE:
     - 2018 - 02 - . 17     # date must be in ISO 8601 format, i.e.-MM-YYYY dd 
datetime:
     -   2018 - 02 -17T15: 02 : 31 is + 08 : 00     # ISO 8601 format used between the time, date, and time using a T-connector, on behalf of the last used time zone +

3.7 special symbols

YAML provides many special symbols can represent different meanings

1. --- YAML can be in the same file, use the --- indicates the start of a document; Springboot such as the definition of the profile:

server:
    address: 192.168.1.100
---
spring:
    profiles: development
    server:
        address: 127.0.0.1
---
spring:
    profiles: production
    server:
        address: 192.168.1.120

key general is not allowed to repeat the same level, where the spring is clearly repeated, but with --- separated, and the equivalent of two configuration files, but wrote a inside.

2. ... and --- with the use, mean the end of a file in a configuration file, and almost on top of the action:

---
time: 20:03:20
player: Sammy Sosa
action: strike (miss)
...
---
time: 20:03:47
player: Sammy Sosa
action: grand slam
...

Use !! do 3. !! YAML forced conversion type in which:

string:
    - !!str 54321
    - !!str true

Here corresponds to the true number 54321 and cast into str type, which is a string type.

--- !!set
- Mark McGwire: 65
- Sammy Sosa: 63
- Sammy Sosa: 63
- Ken Griffy: 58

Parsing the array is a set, simple to understand, the content of the conversion is: [{Ken Griffy = 58}, {Mark McGwire = 65}, {Sammy Sosa = 63}], duplicate Sammy Sosa removed.

4.> string can wrap, | reservation line breaks, sometimes we need to wrap text or special characters you want to keep it, does not work, it would need to use this symbol:

accomplishment: >
 Mark set a major league
 home run record in 1998.
stats: |
 65 Home Runs
 0.278 Batting Average

Read the results:

stats=65 Home Runs
 0.278 Batting Average,


accomplishment=Mark set a major league home run record in 1998.

You can see stats retain the line breaks, and accomplishment allows us to wrap YAML way to write the configuration, but is actually read out his string. Then | wysiwyg configuration is suitable format has configuration items, pay attention to | need to have a space.

Basic grammar we usually use it so much, to fully meet our usual configuration uses more advanced usage can refer to the official documentation.

The use of YAML configuration

4.1 Adding a YAML configuration file

Let's add a YAML configuration file, configuration is a person, we are going to inject this data into our java entity to:

person:
    name: songlin
    age: 1
    hobbies:
      - running
      - reading
      - swiming
    house:
      address: 河南郑州
      area: 90

Adding a person class:

package com.example.demo.domain;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@ConfigurationProperties(prefix = "person")
@Component
public class Person {
    private String name;
    private Integer age;
    private List<String> hobbies;

    private Map<String,String> house;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", hobbies=" + hobbies +
                ", house=" + house +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public List<String> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }

    public Map<String, String> getHouse() {
        return house;
    }

    public void setHouse(Map<String, String> house) {
        this.house = house;
    }
}

And then run the test unit tests:

package com.example.demo;

import com.example.demo.domain.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    @Autowired
    private Person person;
    @Test
    public void contextLoads() {
        System.out.println(person);
    }

}

Run directly input data person will find the console instance, that we implantation success.

V. Summary

Benpian explain the use of YAML configuration files, in springboot is also recommended to use this way to do the configuration file, of course springboot also supported properties as a configuration file, using the methods are the same.

Guess you like

Origin www.cnblogs.com/lookings/p/11539817.html