1. Writing format of yml configuration file
The format is a property name separated by '.' in a normal configuration file, which is': 'and newline.
Example:
//Common format spring.datasource.driver-class-name=com.mysql.jdbc.Driver //yml format spring: datasource: driver-class-name: com.mysql.jdbc.Driver
Note:
1. The annotation format in the configuration file is
Comments
2. There are two letters difference between spring and dataSource.
3. There is a colon and a space between the attribute and the value. It is not written directly after the colon.
2. Take the common key value in the controller layer
Take the value with the annotation @ Value("${property name}").
controller layer values are generally assigned to properties.
@Value("${offcn_ip}")
private String port;
@RequestMapping("/one")
public String getOne(){
return port;
}
3. Take pojo object
1. Write a pojo object in the configuration file
user: username: zhangsan age: 23 id: 1
2. Write entity class
The @ ConfigurationProperties annotation must be present in the entity class, and the prrfix prefix must be specified.
@ConfigurationProperties(prefix = "user") public class User { private String username; private Integer age; private Integer id; public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Override public String toString() { return "User{" + "name='" + username + '\'' + ", age=" + age + ", id=" + id + '}'; } }
3, use
@RestController @EnableConfigurationProperties({User.class}) public class Yml { @Autowired User user; @RequestMapping("/one") public String getOne(){ return user.toString(); } }
The EnableConfigurationProperties annotation needs to be added to the calling class or to the starting class SpringbootSimpleApplication.
This is a simple call to the content in the yml configuration file, and data can be obtained by accessing the request path.