<!-- 配置文件要用到的jar包 processor --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
说明:配置文件中的前缀需要全部小写,不能出现大写。 例如下面的 data
#map 第一种方式 data.person.name=zhangsan data.person.sex=man data.person.age=11 data.person.url=xxxxxxxx #map 第二种方式 data.person[name]=zhangsan data.person[sex]=man data.person[age]=11 data.person[url]=xxxxxxxx #list 第一种方式 data.list[0]=apple0 data.list[1]=apple1 data.list[2]=apple2 #list 第二种方式 data.list=apple0,apple1,apple2,\ apple3,apple4,apple5
#要注意的地方是 属性名 要与 XXX.properties中的参数的名保持一致,详见属性注解 //@Configuration 标识这是一个配置类 @Component("configData") // 添加到bean容器时指定其名为 configData @ConfigurationProperties(prefix = "data") // 读取前缀为 data 的内容 //如果只有一个主配置类文件,@PropertySource可以不写 @PropertySource("classpath:XXX.properties") // @PropertySource(value = { "classpath:config/XXX.properties" }, encoding = "utf-8") public class DataConfig{ /** * data.person.name * 这里map名需要和XXX.properties中的参数data.person.name的person一 致 */ private Map<String, String> person = new HashMap<>(); /** * data.list * 这里list名需要和XXX.properties中的参数data.list的list一致 */ private List<String> list = new ArrayList<>(); /** * 编写get,set方法方便使用 */ public Map<String, String> getPerson() { return person; } public void setPerson(Map<String, String> person) { this.person = person; } public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } }
@Autowired @Qualifier("configData") // 指定注入bean的名称,提高注入准确性 private DataConfig dataConfig; @Test public void contextLoads() { Map<String, String> person = dataConfig.getPerson(); List<String> list = dataConfig.getList(); System.out.println("image:"+JSONObject.fromObject(person).toString()); System.out.println("list:"+ JSONArray.fromObject(list).toString()); }
输出结果
image:{"sex":"man","name":"zhangsan","age":"11","url":"xxxxxxxx"} list:["apple0","apple1","apple2","apple3","apple4","apple5"]