3. java SpringBoot yaml configuration injection

yaml grammar learning

configuration file

SpringBoot uses a global configuration file with a fixed name

  • application.properties

    • Syntax structure: key=value

  • application.yml

    • Syntax structure: key: space value

Function of configuration file: modify the default value of SpringBoot automatic configuration, because SpringBoot is automatically configured at the bottom;

For example, we can modify the default startup port number of Tomcat in the configuration file! Test it!

server.port=8081

yaml overview

YAML is a recursive abbreviation of "YAML Ain't a Markup Language". When developing this language, YAML actually means "Yet Another Markup Language"

This language is data centric, not markup language focused!

Most of the previous configuration files were configured using xml; For example, a simple port configuration, let's compare yaml and xml

Traditional xml configuration:

<server>    <port>8081<port></server>

yaml configuration:

server:   prot: 8080

yaml basic syntax

Note: strict grammar requirements!

1. Spaces cannot be omitted

2. The hierarchical relationship is controlled by indentation. As long as a column of data aligned on the left is at the same level.

3. Attributes and values are case sensitive.

Literal: normal value [number, Boolean, string]

The literal quantity can be written directly after the string. By default, double quotation marks or single quotation marks are not added to the string;

k: v

be careful:

  • "" double quotation marks will not escape the special characters in the string, and the special characters will be used as the meaning they want to express;

    For example: name: "kuang \n shen" output: kuang , line feed , shen

  • '' single quotation mark, which will escape special characters, and the special characters will eventually be output like ordinary characters

    For example: name: 'kuang \n shen' output: kuang \ n

Object, Map (key value pair)

#Object, Map format K: V1: V2:

Write the attribute and value relationship of the object in the next line, and pay attention to the indentation; For example:

student:    name: qinjiang    age: 3

Inline writing

student: {name: qinjiang,age: 3}

Array (List, set)

Use the - value to represent an element in the array, for example:

pets: - cat - dog - pig

Inline writing

pets: [cat,dog,pig]

Modify the default port number of SpringBoot

Add the parameter of port number in the configuration file to switch ports; ​​​​​​​

server:  port: 8082

Injection profile

yaml file is more powerful because it can directly inject matching values into our entity classes!

yaml injection profile

1. Create a new file application. In the resources directory of the springboot project yml

2. Write an entity class Dog;

package com.kuang.springboot.pojo;@Component  //Register bean s in the container public class dog {private string name; private integer age; / / parameterless construction, get, set methods, toString() methods}

3. Think about how we used to inject attribute values into bean s@ Value, test the dogs:

@Component //Register beanpublic class dog {@ value ("ahuang") private string name; @ value ("18") private integer age;}

4. Inject and output the dog under the test class of SpringBoot; ​​​​​​​

@SpringBootTestclass DemoApplicationTests {    @Autowired //Automatically inject the dog into dog dog dog@ Test public void contextloads() {system. Out. Println (dog); / / print the dog object}}

The result is successfully output and @ Value is successfully injected. This is our original method, right.

5. We are writing a more complex entity class: the Person class

@Component //Register bean s in the container public class person {private string name; private integer age; private Boolean happy; private date birth; private map < string, Object > maps; private list < Object > lists; private dog dog; / / parameterless construction, get, set methods, toString() methods}

6. Let's use yaml configuration for injection. When you write, pay attention to the differences and advantages. We write a yaml configuration!

person:  name: qinjiang  age: 3  happy: false  birth: 2000/01/01  maps: {k1: v1,k2: v2}  lists:   - code   - girl   - music  dog:    name: Wangcai    age: 1

7. We have written all the values of the person object just now. Now let's inject them into our class!

/*@ConfigurationProperties Function: map the value of each attribute configured in the configuration file to this component; Tell SpringBoot to bind all properties in this class to the relevant configuration in the configuration file. Parameter prefix = "person": correspond all properties under person in the configuration file one by one*/@Component //register bean@ConfigurationProperties (prefix = "person")public class Person {    private String name;    private Integer age;    private Boolean happy;    private Date birth;    private Map<String,Object> maps;    private List<Object> lists;    private Dog dog;}

8. IDEA prompts that the springboot configuration annotation processor is not found. Let's look at the document. We can look at the document and find a dependency!

<!-- After importing the configuration file processor, you will be prompted to restart the configuration file binding --><dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-configuration-processor</artifactId>  <optional>true</optional></dependency>

9. After confirming that the above configurations are OK, let's test in the test class:

@SpringBootTestclass DemoApplicationTests {    @Autowired    Person person; //Automatically inject person into @ test public void contextloads() {system. Out. Println (person); / / print person information}}

Result: all values are injected successfully!

yaml configuration injection into the entity class is completely OK!

Classroom test:

1. If the key value of the configuration file is different from the value of the attribute, the result output is null and the injection fails

2. After configuring a person2, point @ ConfigurationProperties(prefix = "person2") to our person2;

Loads the specified configuration file

@PropertySource: load the specified configuration file;

@configurationProperties: get the value from the global configuration file by default;

1. Let's create a new person in the resources directory Properties file

name=kuangshen

2. Then specify in our code to load person Properties file

@PropertySource(value = "classpath:person.properties")@Component //Register beanpublic class person {@ value ("${name}") private string name;...}

3. Output the test again: the specified configuration file is bound successfully!

Profile placeholder

Configuration files can also write placeholders to generate random numbers

person:    name: qinjiang${random.uuid} # random uuid    age: ${random.int}  # Random int happy: false birth: 2000 / 01 / 01 maps: {K1: V1, K2: V2} lists: - Code - Girl - music dog: name: ${person.hello:other}_ Wangcai age: 1

Review the properties configuration

The yaml methods we used above are the simplest and most commonly used in development; It is also recommended by springboot! Let's talk about other implementation methods. The reason is the same; Write or write like that; In addition to yml, the configuration file also has the properties we used before. We didn't talk about it. Let's talk about it!

[note] when writing the properties configuration file in Chinese, there will be garbled codes. We need to set the encoding format to UTF-8 in the IDEA;

Settings -- > configured in fileencodings;

Test steps:

1. Create a new entity class User

@Component //Register beanpublic class user {private string name; private int age; private string sex;}

2. Edit profile user properties

user1.name=kuangshenuser1.age=18user1.sex=male

3. We use @ Value on the User class for injection!

@Component //register bean@PropertySource(value = "classpath:user.properties")public class User {/ / directly use @ value ("${user. Name}") / / get private string name from the configuration file@ Value ("#{9 * 2}") / / #{spel} spring expression private int age@ Value ("male") / / literal private String sex;}

4. Springboot test

@SpringBootTestclass DemoApplicationTests {    @Autowired    User user;    @Test    public void contextLoads() {        System.out.println(user);    }}

Result normal output:

Comparison summary

@Value is not friendly to use! We need to assign a value to each attribute separately, which is troublesome; Let's look at a function comparison diagram

1. @ ConfigurationProperties only needs to be written once, and @ Value needs to be added to each field

2. Loose binding: what does that mean? For example, the last name written in my yml is the same as lastName, and the letters followed by - are capitalized by default. This is loose binding. You can test it

3. JSR303 data verification, that is, we can add a layer of filter verification in the field to ensure the legitimacy of the data

4. Complex type encapsulation. Objects can be encapsulated in yml, but value is not supported

Conclusion:

Values can be obtained by configuring yml and configuring properties. yml is highly recommended;

If we only need to obtain a value in the configuration file in a business, we can use @ value;

If we specially write a JavaBean to map one by one with the configuration file, we can directly @ configurationProperties. Don't hesitate!

Keywords: Java Spring Spring Boot

Added by phpnewbie81 on Mon, 27 Dec 2021 21:45:26 +0200