Springboot 使用 @ConfigurationProperties 和 @PropertySource 來讀取指定位置的 .peoperties 配置文件,並將配置文件中的 value 值與對應的實體類進行綁定,具體步驟如下:
1、配置文件
// 基本數據類型的值與實體類中屬性進行映射綁定
person.name=小毛毛
person.age=21
person.height=157.00
// 數組元素與實體類中 hobby 屬性進行映射綁定
person.hobby[0]=LOL
person.hobby[1]=KFC
person.hobby[2]=COFFE
// List集合中元素與實體類 pets 屬性進行映射綁定
person.pets[0].name=Husky
person.pets[0].age=2
person.pets[0].color=gray
person.pets[1].name=persian
person.pets[1].age=3
person.pets[1].color=orange
// Map集合中元素與實體類中 featureLevel 屬性進行映射綁定
person.featureLevel.clever=10
person.featureLevel.lovely=8
person.featureLevel.funny=8
2、實體類 Person
// 將 Person 注入到 IOC 容器中,只有容器中的組件才能使用 Springboot 的強大功能
@Configuration
// 將 person 下級的 key 與實體類進行映射綁定,並為其注入屬性值
@ConfigurationProperties(prefix = "person")
// 加載指定位置的 properties 配置文件
@PropertySource("classpath:config/application.properties")
// 該類省略了 set/get 方法
public class Person {
// 基本數據類型的屬性
private String name;
private Integer age;
private double height;
// 數組
private String[] hobby;
// List 集合
private List<Pet> pets;
// Map 集合
private Map<String, String> featureLevel;
}
3、實體類 Pet (省略 get/set/toString)
public class Pet {
private String name;
private String age;
private String color;
}
4、測試類
@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot01ApplicationTests {
@Autowired
private ApplicationContext ioc;
@Test
public void testProperties() {
Person person = ioc.getBean("person", Person.class);
System.out.println(person);
}
}
5、測試結果
Person{
name='小毛毛',
age=21,
height=157.0,
hobby=[LOL, KFC, COFFE],
pets=[
Pet{name='Husky', age='2', color='gray'},
Pet{name='persian', age='3', color='orange'}
],
featureLevel={clever=10, lovely=8, funny=8}
}