1、yml配置文件書寫格式
格式是在普通配置文件中以“.”分割的屬性名稱,該為“: ”和換行。
例子:
//普通格式 spring.datasource.driver-class-name=com.mysql.jdbc.Driver //yml格式 spring: datasource: driver-class-name: com.mysql.jdbc.Driver
注意:
1、在配置文件中的注解格式是
#注解
2、在spring與dataSource是相差兩個字母的。
3、在屬性與值之間有一個冒號和空格,並不是冒號之后直接書寫。
2、在controller層中取普通鍵值
以注解@Value("${屬性名}"),來取值。
controller層取值一般會賦值給屬性。
@Value("${offcn_ip}")
private String port;
@RequestMapping("/one")
public String getOne(){
return port;
}
3、取pojo對象
1、在配置文件中書寫一個pojo對象
user: username: zhangsan age: 23 id: 1
2、編寫實體類
在實體類中必須有@ConfigurationProperties 這個注解,並且指定prrfix前綴。
@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、使用
@RestController @EnableConfigurationProperties({User.class}) public class Yml { @Autowired User user; @RequestMapping("/one") public String getOne(){ return user.toString(); } }
EnableConfigurationProperties注解需要加在調用類上,或者加在啟動類SpringbootSimpleApplication上也可以。
這就是一個簡單的對於yml配置文件中內容的調用,訪問請求路徑便能獲得數據。