接上篇: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); } }
結果: