SpringBoot - learn more about configuration files

I configuration file SpringBoot uses a global configuration file with a fixed name; •application.properties •application.yml

1. Function of configuration file: Modify the default value of SpringBoot auto configuration; SpringBoot is automatically configured at the bottom;

YAML(YAML Ain't Markup Language) YAML A Markup Language: is a markup language YAML isn't Markup Language: not a markup language;

Markup Language:

Previous configuration files; Most of them use XXXX XML file; YAML: data centric, more suitable for configuration files than json, xml, etc; YAML: Configuration Example

server:
  port: 8081

XML:

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

2. Basic grammar k: (space) v: indicates a pair of key value pairs (space must be); a. Indent the space to control the hierarchical relationship; As long as a column of data is left aligned, it is at the same level; b. Attributes and values are also case sensitive

server:
    port: 8081
    path: /hello

3. Writing method of value a. Literal: ordinary value (number, string, Boolean) B. K: V: write it literally; c. The string does not need single quotation marks or double quotation marks by default; d. "": double quotation marks; Special characters in the string will not be escaped; Special characters will be used as the meaning they want to express

 name: "zhangsan \n lisi": 
Output; zhangsan Line feed lisi

e. ': single quotation mark; Special characters will be escaped, and the special characters will eventually be just ordinary string data

​ name: 'zhangsan \n lisi': 
Output; zhangsan \n lisi

f. Object, Map (attribute and value) (key value pair): k: v: write the relationship between the attribute and value of the object in the next line; Note that the indented object is still k: v

friends:
       lastName: zhangsan
       age: 20

Inline writing:

friends: {lastName: zhangsan,age: 18}

g. Array (List, Set): Use the - value to represent an element in the array

pets:
 - cat
 - dog
 - pig

Inline writing:

pets: [cat,dog,pig]

II Profile value injection When the configuration file is injected, the application will be loaded at the same time Properties and yml, but the priority of properties is higher. The configuration of yml will be used for the content not configured in properties.

yml profile

person:
    lastName: hello
    age: 18
    boss: false
    birth: 2017/12/12
    maps: {k1: v1,k2: 12}
    lists:
      - lisi
      - zhaoliu
    dog:
      name: puppy
      age: 12

properties configuration file:

person.last_name=Zhang San
person.age=18
person.boss=true
person.birth=2010/01/01
person.maps.k1=mmm
person.maps.v1=aaa
person.maps.k2=dog
person.maps.v2.dog.name=xiaobei
person.maps.v2.dog.age=3
person.lists={abc,def,ghi}
person.dog.name=wangcai
person.dog.age=4

javaBean:

/**
 * Map the value of each attribute configured in the configuration file to this component
 * @ConfigurationProperties: Tell SpringBoot to bind all the attributes in this class to the relevant configuration in the configuration file;
 *      prefix = "person": Which of the following attributes in the configuration file is mapped one by one
 *
 * The @ ConfigurationProperties function provided by the container can only be used if this component is a component in the container;
 *
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {

    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

We can import the configuration file processor, and we will be prompted to write the configuration later

<!--When you import the configuration file processor, you will be prompted to bind the configuration file-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
@Comparison between Value and @ ConfigurationProperties

a. Loose binding: attribute matching rules Standard method: person firstName Method 1 capitalize with - person first-name Method 2: in words_ person.first_name

b. Spiel: #{expression} various operators can be used in the expression

c.JSR303 data verification: verify the format of attributes. When verifying, mark @ Validated on the class. The common verification of fields include @ email (whether it is a legal email address), @ notnull (whether it is not empty), etc

d. Complex types: such as map, class, etc

They can get values from both configuration files yml and properties; If you only need to obtain a Value in the configuration file in a certain business logic, use @ Value; If a javaBean is specially written to map with the configuration file, we can directly use @ ConfigurationProperties;

Configuration file injection value data verification

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="Literal / ${key} get value from environment variable and configuration file / #{spiel} "> < / property >
     * <bean/>
     */

   //lastName must be in mailbox format
    @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

@PropertySource: load the specified configuration file;

/**
 * Map the value of each attribute configured in the configuration file to this component
 * @ConfigurationProperties: All properties in this configuration file will be told to bind with spring boot;
 *      prefix = "person": Which of the following attributes in the configuration file is mapped one by one
 *
 * The @ ConfigurationProperties function provided by the container can only be used if this component is a component in the container;
 *  @ConfigurationProperties(prefix = "person")Get the value from the global configuration file by default;
 *
 */
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="Literal / ${key} get value from environment variable and configuration file / #{spiel} "> < / property >
     * <bean/>
     */

   //lastName must be in mailbox format
   // @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

@ImportResource: import the Spring configuration file to make the content in the configuration file effective; There is no Spring configuration file in Spring Boot, and the configuration file written by ourselves cannot be recognized automatically; If you want the Spring configuration file to take effect, load it@ ImportResource is marked on a configuration class and in beans Classes configured in XML can no longer be injected with properties and yml

@ImportResource(locations = {"classpath:beans.xml"})
Import Spring Make your profile effective

Write Spring configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>

SpringBoot recommends adding components to the container; Full annotation is recommended 1. Configuration class @ configuration - > spring configuration file 2. Use @ Bean to add components to the container

/**
 * @Configuration: Indicates that the current class is a configuration class; Is to replace the previous Spring configuration file
 *
 * Add components in the configuration file with the < bean > < bean / > tag
 *
 */
@Configuration
public class MyAppConfig {

    //Add the return value of the method to the container; The default id of this component in the container is the method name
    @Bean
    public HelloService helloService02(){
        System.out.println("Configuration class@Bean Added components to the container...");
        return new HelloService();
    }
}

Keywords: Spring Boot

Added by webstyler on Wed, 09 Feb 2022 16:59:27 +0200