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

编程入门 行业动态 更新时间:2024-10-28 11:29:24
本文介绍了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 无法将属性文件映射到变量

本文发布于:2023-11-17 05:41:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609028.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   属性   文件   Springboot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!