1、配置文件application.properties添加如下參數:
#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
2、寫一個PersonConfig類,用來讀取配置信息
@Configuration @ConfigurationProperties(prefix = "data") @Data //如果只有一個主配置類文件,@PropertySource可以不寫 @PropertySource("classpath:application.properties") public class PersonConfig { /** * data.person.name * 這裡map名需要和application.properties中的參數一致 */ private Map person = new HashMap<>(); /** * data.list * 這裡list名需要和application.properties中的參數一致 */ private List list = new ArrayList<>(); }
3、測試類測試
@Autowired private PersonConfig personConfig; @Test public void contextLoads() { Map person = personConfig.getPerson(); List list = personConfig.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"]
對象
#### 自定義List集合,首先在application.yml文件中配置 custom: mail[0]: username: [email protected] password: axxx mail[1]: username: [email protected] password: axxx // 然後配置接受類 @Data @Configuration @ConfigurationProperties("custom") public class Custom { private List mail; } // MailInfo類的內容是 @Data public class MailInfo { private String username; private String password; }
自定義數組
#### 自定義數組,首先在application.yml文件中配置 custom: ignored-token-path: /base/xx/login, /xx/**, /xx/hfc/test ignored-role-path: /base/xx/logout, /base/xx/queryMenus //然和配置接受類 @Data @Configuration @ConfigurationProperties("custom") public class Custom { private String[] ignoredTokenPath; private String[] ignoredRolePath; }