springboot-------yml configuration read

Read configuration content

Three ways:

  1. @Value
  2. Environmen
  3. @ConfigurationProperties

the first way

Directly add the corresponding attribute to the class that needs to refer to the key-value pair, and use @Value to mark it, and then it can be used or directly accessed.
The values ​​here are all custom written in the configuration file

the second way

Configure the Environment, as shown in the figure, use @Autowired to automatically identify the spring container, and then call the properties in it. Use the getProperty() method to call the relevant property to get the value.
insert image description here
insert image description here

third method

Configure a class separately for implementation, as shown in the figure, first mark the class as a component that can be recognized by spring, then use the ConfigurationProperties annotation to mark it, and then the parameters in brackets can be used to determine which one it is imported from, in our yml file In , there are relevant attributes for corresponding matching.
insert image description here
insert image description here

name: abc

# 对象
person:
#  参数引用 ${
    
    }
#  name: ${
    
    name}
  name: zhangsan
  age: 20
  address:
    - beijing
    - shanghai


person2: {
    
    name: zhangsan, age: 21}

# 数组
address:
  - beijing
  - shanghai

# 数组的行内写法
address2:  [beijing, shanghai]

The call method test is as follows:

Test Results

Solve related minor problems

insert image description here
This situation occurs when configuring ConfigurationProperties annotations. This is not a mistake. It can be solved by configuring dependencies. Adding this dependency in prom.

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

Guess you like

Origin blog.csdn.net/qq_53259920/article/details/123398346