1. 程式人生 > >Springboot讀取自定義的yml文件中的List對象

Springboot讀取自定義的yml文件中的List對象

pat setprop 必須 rop rip aml 無法 vat this

Yml文件(novellist.xml)如下:

novellist:
list:
- name: 笑傲江湖
type: 武俠
master: 令狐沖
author: 金庸
description: 小說以通過敘述華山派大弟子令狐沖的經歷,反映了武林各派爭霸奪權的歷程。
- name: 誅仙
type: 仙俠
master: 張小凡
author: 蕭鼎
description: 該小說以“天地不仁,以萬物為芻狗”為主題,講述了青雲山下的普通少年張小凡的成長經歷以及與兩位奇女子淒美的愛情故事,整部小說構思巧妙、氣勢恢宏,開啟了一個獨具魅力的東方仙俠傳奇架空世界,情節跌宕起伏,人物性格鮮明,將愛情、親情、友情與波瀾壯闊的正邪搏鬥、命運交戰匯集在一起,文筆優美,故事生動。
- name

: 英雄誌
type: 武俠
master: 觀海雲遠
author: 孫曉
description: 《英雄誌》為一虛構中國明朝歷史的古典小說,借用明英宗土木堡之變為背景,以復辟為舞臺,寫盡了英雄們與時代間的相互激蕩,造反與政變、背叛與殉道

將List對象轉化為List<Map<String, String>>或者List<Novel>,其中prefix中的novelist必須小寫,否則報錯:

@Component
@ConfigurationProperties(prefix = "novellist")
public class

NovelList {

private List<Map<String, String>> list;

public List<Map<String, String>> getList() {
return list;
}

public void setList(List<Map<String, String>> list) {
this.list = list;
}

@Override
public String toString() {
return "NovelList{"
+
"list=" + list +
‘}‘;
}
}

將yml中的內容放入,application.yml文件中正常,自定義novellist.yml文件中無法找到。使用@ConfigurationProperties註解,只能用於properties文件。

解決方式:可以通過PropertySourcePlaceholderConfigurer來加載yml文件,暴露yml文件到spring environment,如下:

@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("novellist.yml"));
configurer.setProperties(yaml.getObject());
return configurer;
}

Springboot讀取自定義的yml文件中的List對象