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

Yml文件(novellist.xml)以下:spring

novellist:
  list:
    - name: 笑傲江湖
      type: 武俠
      master: 令狐沖
      author: 金庸
      description: 小說以經過敘述華山派大弟子令狐沖的經歷,反映了武林各派爭霸奪權的歷程。
    - name: 誅仙
      type: 仙俠
      master: 張小凡
      author: 蕭鼎
      description: 該小說以「天地不仁,以萬物爲芻狗」爲主題,講述了青雲山下的普通少年張小凡的成長經歷以及與兩位奇女子悽美的愛情故事,整部小說構思巧妙、氣勢恢宏,開啓了一個獨具魅力的東方仙俠傳奇架空世界,情節跌宕起伏,人物性格鮮明,將愛情、親情、友情與波瀾壯闊的正邪搏鬥、命運交戰聚集在一塊兒,文筆優美,故事生動。
    - name: 英雄志
      type: 武俠
      master: 觀海雲遠
      author: 孫曉
      description: 《英雄志》爲一虛構中國明朝歷史的古典小說,借用明英宗土木堡之變爲背景,以復辟爲舞臺,寫盡了英雄們與時代間的相互激盪,造反與政變、背叛與殉道app

將List對象轉化爲List<Map<String, String>>或者List<Novel>,其中prefix中的novelist必須小寫,不然報錯:ide

@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 +
                '}';
    }
}this

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

解決方式:能夠經過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;
}ip

相關文章
相關標籤/搜索