1. 程式人生 > 實用技巧 >SpringBoot02--將application.yaml配置檔案中的屬性和元件中的屬性進行繫結

SpringBoot02--將application.yaml配置檔案中的屬性和元件中的屬性進行繫結

1、在resource下建立一個application.yaml檔案

person:
  name: zhangsan
  age: 20
  birth: 1998/02/01
  list:
    - l1
    - l2
    - l3
  map: {k1: v1,k2: v2}

2、建立一個Person類。

@ConfigurationProperties(prefix = "person"):將yaml檔案中字首是person下的屬性與Peron類中的屬性繫結。
如果要使
@ConfigurationProperties(prefix = "person")生效,需要將元件註冊到容器中。所以使用@Component註冊元件。
package com.killbug.helloworld.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;
@Component
@ConfigurationProperties(prefix = "person")
public class
Person { private String name; private int age; private Date birth; private List list; private Map map; 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 Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public List getList() { return list; } public void setList(List list) { this.list = list; } public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", birth=" + birth + ", list=" + list + ", map=" + map + '}'; } }