接上篇:SpringBoot/Spring使用@Value进行属性绑定(传智播客代码)
ConfigurationProperties注解默认会从全局配置文件读取属性,当属性多的时候,主配置文件(
application.yml、application.properties)会臃肿,因此有必要把某一类别属性单独分开配置
@PropertyResource读取指定配置文件
该注解的value支持string数组,可以填写多个配置文件路径,例如
@PropertyResource(value={"aaa.properties","classpath:bbb.properties"})
Person.java
package com.atguigu.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@PropertySource(value = {"classpath:person.properties"})
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
配置文件person.properties
person.lastName=李四
person.age=18
person.boss=false
person.birth=2017/12/12
person.maps.k1=v1
person.maps.k2='zhangsan \nlisi'
person.maps.k3="zhangsan \nlisi"
person.lists=[lisi, zhaoliu]
person.dog.name=happy
person.dog.age=5
测试用例
package com.atguigu;
import com.atguigu.bean.Person;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.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
@Slf4j
class DemoApplicationTests {
@Autowired
Person person;
@Test
void customPropertiesTest()
{
log.info("{}",person);
}
}
结果: