Springboot无法将属性文件映射到变量

时间:2019-05-31 17:46:08

标签: java spring-boot yaml

我想在springboot中用Map<String, List<String>>在yaml文件之间映射值

country.yml文件:

entries:
  map:
     MY:
      - en
      - zh

SampleConfig文件:

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("entries")
public class SampleConfig {

    private Map<String, List<String>> map = new HashMap<>();

    @Bean
    public void bean1(){
        System.err.println("map has size: "+map.size());
    }
}

但是map.size()始终为0,不确定我做错了什么。

3 个答案:

答案 0 :(得分:2)

有两个问题

1)默认情况下,spring会在默认位置查找application.ymlapplication.properties

要解决上述问题,您可以使用application.yml代替country.yml

2)您可以使用@PropertySource加载任何外部属性文件,但此注释不支持yml

24.7.4 YAML Shortcomings您不能对@PropertySource文件使用yml

  

无法使用@PropertySource批注来加载YAML文件。因此,在需要以这种方式加载值的情况下,需要使用属性文件。

How to read yml file using Spring @PropertySource

答案 1 :(得分:2)

这将起作用并打印出CountryData : {MY=[en, zh]}

,但请务必阅读Deadpool的答案。

hack 在此处用“国家/地区”覆盖默认配置名称“应用程序”

在示例中,

我是通过System属性进行设置的,但是通过 java -jar mycountryapp.jar --spring.config.name=country应该工作正常

@SpringBootApplication
public class Application {

    static {
      System.setProperty("spring.config.name", "country");
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

@Service
class CountryService {
  private final CountryData countryData;
    public CountryService(CountryData countryData) {
        this.countryData = countryData;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void showCountryDataOnStartup() {
      System.err.println("CountryData : " + countryData.getMap());
    }

}

@Configuration
@ConfigurationProperties(prefix = "entries")
class CountryData {

    Map<String, List<String>> map;

    public Map<String, List<String>> getMap() {
        return map;
    }

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

}

答案 2 :(得分:1)

假设您的应用程序正在country.yml中选择配置(我也会检查)-您需要使用getter和setter才能使其正常工作。只需添加:

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("entries")
public class SampleConfig {

    private Map<String, List<String>> map = new HashMap<>();

    public Map<String, List<String>> getMap(){
        return map;
    }
    public void setMap(Map<String, List<String>> map){
        this.map=map;
    }

}
相关问题