【问题标题】:load yaml values at application startup in spring在春季应用程序启动时加载 yaml 值
【发布时间】:2018-09-19 04:57:04
【问题描述】:

我有一些 .yml 文件,想在应用程序启动时加载所有文件。我希望它们被加载到某个 bean 对象中。在此之后,我应该能够在应用程序的任何地方访问 yml 值。有可能吗?

下面是yml。

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: 

【问题讨论】:

    标签: spring spring-boot yaml


    【解决方案1】:

    是的,您可以使用 @ConfigurationProperties(prefix = "country") link1link2 注释将所有属性加载到 bean 类中,因为 spring 创建了 bean,您可以在需要的位置自动装配这个 bean

    @Configuration
    @ConfigurationProperties(prefix = "country")
    public class countryListConfig {
    
    private List<countryList> list;
    
    public List<countryList> getList() {
    return list;
     }
    
     public void setList(List<countryList> list) {
     this.list = list;
     }
    
     public static class countryList {
     private String CountryName;
     private String CountryCode;
     // getters and setters
    
     }
    

    如果你想在应用程序的任何地方使用这些属性,那么你应该将它们声明为静态,因为你不能直接从 yml 文件使用 setter 机制自动装配静态变量

    private static List<countryList> staticlist;
    
    
     public void setList(List<countryList> list) {
     staticlist = list;
     }
    

    或者您也可以将 countryListConfig bean 自动连接到任何实用程序类中的静态引用,并在整个应用程序中使用该 bean

    【讨论】:

    • 我在上面尝试过,但没有成功。我只使用它,但没有使用 autowire。
    • 只是为了通知我的 yml 文件名是 country.yml。是不是导致了这个问题?
    • 使用属性资源注解 @PropertySource(name = "props", value = "classpath:country.properties", ignoreResourceNotFound = false) 并且在 yml 中将 country 更改为 country.list
    猜你喜欢
    • 1970-01-01
    • 2018-06-15
    • 2018-05-20
    • 1970-01-01
    • 2015-03-12
    • 2020-08-23
    • 2015-12-23
    • 2015-11-11
    • 2018-09-04
    相关资源
    最近更新 更多