@ConfigurationProperties 用于將配置文件(如 application.properties 或 application.yml)中的屬性批量綁定到一個 Java Bean 中。
1. 定義配置文件
在 application.properties 或 application.yml 中定義一組具有相同前綴的屬性。
application.yml :
person:id: 1name: tomhobby:- play- read- sleepfamily:- father- mothermap:k1: v1k2: v2pet:type: dogname: kity
application.properties :
person.id=1
person.name=tom
person.hobby=play,read,sleep
person.family=father,mother
person.map.k1=v1
person.map.k2=v2
person.pet.type=dog
person.pet.name=kity
2. 創建配置類
創建一個 Java Bean,并使用 @ConfigurationProperties 注解將配置文件中的屬性綁定到該 Bean 中。
Person.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;import java.util.Arrays;
import java.util.List;
import java.util.Map;@Component // 用于將Person類作為Bean注入到Spring容器中
@ConfigurationProperties(prefix = "person") // 將配置文件中以person開頭的屬性注入到該類中
public class Person {private int id; //idprivate String name; //名稱private List hobby; //愛好private String[] family; //家庭成員private Map map;private Pet pet; //寵物//省略getter,setter,toString
}
Pet.java
public class Pet {private String type;private String name;//省略getter,setter,toString
}
3. 測試方法
@SpringBootTest
public class WebTest {@Autowiredprivate Person person;@Testpublic void test(){System.out.println(person);}}