Spring boot 註解 ConfigurationProperties 的使用

原創自 第一勺金spring

00

最近在學習使用 spring boot。發現其中 @ConfigurationProperties這個註解使用的比較多。搜了比較多的文檔都是英文,避免之後忘記,這裏我也總結下它的使用方法。bash

01

開始建立一個Spring boot項目,我喜歡用官網的平臺建立 start.spring.io/app

首先依賴spring-boot

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

如今 spring boot使用 .yml 格式貌似是「開發正確」,因此這裏將 application 的格式改爲 .yml學習

@ConfigurationProperties的做用是從配置文件中讀取數據,我也不直接拿項目中的數據來舉例。直接簡單粗暴點。經過配置獲取單個屬性、集合 ,常見就這兩種,不可能還從中獲取 map 數據類型的數據不成。測試

獲取屬性數據

在 application 中添加以下對象屬性數據ui

person:
    name: guozh
    age: 25
    adress: shenzheng
複製代碼

建立以下對象this

@Component
@ConfigurationProperties(prefix = "person")
public class ConfigData {

    private String name;
    private int age;
    private String adress;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAdress() {
        return adress;
    }

    public void setAdress(String adress) {
        this.adress = adress;
    }
}

複製代碼

注意:spa

  • 經過prefix 定位到以 person 開頭
  • 保證 屬性名字 和 application.yml 中同樣,這樣就能自動匹配
  • 添加 get set 方法,一個都不能少,否則就啓動不成功

建立個 controller 來測試下,能不能獲取.net

@RestController
public class PersonController {

    @Autowired
    private ConfigData configData;

    @RequestMapping("/getPerson")
    public String getPerson(){

        return configData.getName()+" "+configData.getAge()+" "+configData.getAdress();
    }


}
複製代碼

大部分是 spring 的內容,不用說了。直接運行

ok 已經獲取。

獲取集合數據

實際上是同理,直接貼代碼。

application.yml

class:
    students:
        - jack
        - tom
        - oliver
複製代碼

StudentData

@Component
@ConfigurationProperties(prefix = "class")
public class StudentData {

    private List<String> students = new ArrayList<>();

    public List<String> getStudents() {
        return students;
    }

    public void setStudents(List<String> students) {
        this.students = students;
    }
}
複製代碼
@RequestMapping("/getStudent")
    public String getStudent(){
        return studentData.getStudents().toString();
    }

複製代碼

原創自 第一勺金

相關文章
相關標籤/搜索