yml文件天然的樹形結構,無疑讓配置和使用變得更加舒適。今天就簡單記錄一下學習yml進行配置的過程。
一.爲了使我們可以使用@ConfigurationProperties註解,我們提前將以下依賴配置在pom.xml當中
<!--yml文件進行配置需要用到的依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
二.編寫我們需要的實體類,與我們的application.yml進行映射,並進行測試
Cat.java
package pojo;
public class Cat {
private String catName;
private Integer catAge;
@Override
public String toString() {
return "Cat{" +
"catName='" + catName + '\'' +
", catAge=" + catAge +
'}';
}
public String getCatName() {
return catName;
}
public void setCatName(String catName) {
this.catName = catName;
}
public Integer getCatAge() {
return catAge;
}
public void setCatAge(Integer catAge) {
this.catAge = catAge;
}
}
Person.java
package pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 將配置文件中的屬性映射到這個組件中
* ConfigurationProperties告訴Springboot將本類中的所有屬性和配置文件中
* 相關的配置進行綁定
* prefix用於指明配置的文件是哪個,命名要與配置文件中的一樣且大小寫敏感
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Cat cat;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", birth=" + birth +
", maps=" + maps +
", lists=" + lists +
", cat=" + cat +
'}';
}
}
application.yml
server:
port: 8081
person:
name: John
age: 18
birth: 1999/09/09
maps:
k1: k1
k2: k2
# 行內寫法,在一行中寫
lists: [lisi,zhaowu]
# lists:
# - lisi
# - zhaowu
cat:
catName: 小小
catAge: 1
測試代碼:
package com.SpringBoot.hello;
import pojo.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 單元測試
* 爲了提前發現缺陷並且在後續開發中避免
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloApplicationTests {
@Autowired
Person person;
@Test
public void contextLoads() {
System.out.println(person);
}
}
我之前的項目結構是這樣的,將pojo與com.SpringBoot.hello放置在同一級,即都在Java目錄下,如圖
這樣的話會導致測試的時候Person類的bean找不到,如圖
解決方案:
將pojo移到com.SpringBoot.hello下即可
好了之後我們就運行一下測試類:
關注公衆號,獲取更多資源
每天進步一點點,開心也多一點點