Springboot 无法将属性文件映射到变量 [英] Springboot failed to map properties file to variable

查看:49
本文介绍了Springboot 无法将属性文件映射到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个带有 Map> 的 yaml 文件之间映射值

i want to map values between a yaml file with a Map<String, List<String>> in springboot

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,不知道我做错了什么.

But the map.size() is always 0, not sure what i do wrong.

推荐答案

this will work and print out CountryData : {MY=[en, zh]}

this will work and print out CountryData : {MY=[en, zh]}

但一定要阅读死侍的答案.

hack 在这里用国家/地区"覆盖默认配置名称应用程序"

the hack is here to override the default configuration name 'application' by 'country'

在示例中,我通过系统属性设置它来完成它,但是通过启动您的应用程序java -jar mycountryapp.jar --spring.config.name=country 应该可以完美运行

in the example, I have done it by setting it via a System property, but starting your application via java -jar mycountryapp.jar --spring.config.name=country should work perfectly

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

}

这篇关于Springboot 无法将属性文件映射到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆