我想在一个带有 Map
i want to map values between a yaml file with a Map<String, List<String>> in springboot
country.yml 文件:
entries: map: MY: - en - zhSampleConfig 文件:
@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 无法将属性文件映射到变量
发布评论