在春季加载yml文件并从yml打印值

时间:2018-09-18 09:03:40

标签: spring spring-boot yaml

我是新来的春天,正在学习。

我有一个country.yml文件,想从该文件中加载值。我怎样才能做到这一点? 如果没有列出,我可以加载值。如果是列表,则会出错(无法解析值“ $ {Country.CountryName}”中的占位符“ Country.CountryName”)) 下面是文件

Country:
-
    CountryName: Afghanistan
    CountryCode: AFG
    CurrencyName: Afghan afghani
    CurrencyCode: AFN
    Region: Asia
    SubRegion: Southern Asia
    LanguageName: Pashto
    LanguageCode: PUS
    PerCapitaRank: 170
-
    CountryName: Åland Islands
    CountryCode: ALA
    CurrencyName: Euro
    CurrencyCode: EUR
    Region: Europe
    SubRegion: Northern Europe
    LanguageName: Swedish
    LanguageCode: SWE
    PerCapitaRank: 

下面是我的代码

ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(YamlTestApplication.class)
                .properties("spring.config.name:CountriesData,applicationTest",
                        "spring.config.location:classpath:/config/")
                .build().run(args);

        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        MutablePropertySources sources = environment.getPropertySources();

        for(PropertySource<?> x : sources) {
            System.out.println(x.getName());
            if(x.getName().startsWith("applicationConfig")) {
                LinkedHashMap<String, OriginTrackedValue> z = (LinkedHashMap<String, OriginTrackedValue>) x.getSource();
                //LinkedHashMap<String, String> a = z.get("Country.CountryName");
                for(Entry<String, OriginTrackedValue> entry : z.entrySet()){

                        System.out.println(entry.getKey() + ": " + entry.getValue());
                    //}
                }
                //System.out.println(z.get("Country.CountryName"));
            }
        }

0 个答案:

没有答案