Read configuration content
Three ways:
- @Value
- Environmen
- @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 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.
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.
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:
Solve related minor problems
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>