Springboot读取自定义的yml文件中的List对象

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;
}

posted @ 2018-12-09 17:54  孤剑者  阅读(23880)  评论(0编辑  收藏  举报