Springboot yml Map List读取
hongweigg 人气:0Springboot yml Map List读取
Springboot 读取yml中的值作为参数,有2种写法:
例子:
已知有如下yml配置:
myapps: 1131f78c313e11e79da3000c298bdf0e: AMS系统 1ae211c543a14cf6981274fec3281f0c: BMS系统 app1: 测试
现在需要将myapps读到配置文件作为配置类。有2种做法:
1、配置类集中放置
也就是说应用中设一个配置类,所有涉及yml配置的类都放置在该类中。
@Configuration @Order(Ordered.HIGHEST_PRECEDENCE) public class MyConfiguration { static Logger log = LoggerFactory.getLogger(MyConfiguration.class); @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } @Value("${px.a.trackerServer}") String trackerServer = ""; @Value("${px.a.disabled:true}") boolean disableA = true; @Bean @ConfigurationProperties(prefix = "px.client") ClientConfigInfo clientConfigInfo(){ ClientConfigInfo clientConfigInfo = new ClientConfigInfo(); return clientConfigInfo; } @Bean @ConfigurationProperties(prefix = "px") MyAppConfiguration myAppConfiguration(){ MyAppConfiguration myAppConfiguration = new MyAppConfiguration (); return myAppConfiguration; } }
这里配置为:
@Bean @ConfigurationProperties(prefix = "px") UdsAppConfiguration udsAppConfiguration(){undefined UdsAppConfiguration udsAppConfiguration = new UdsAppConfiguration(); return udsAppConfiguration; }
2、配置类单独放置
也就是说把MyAppConfiguration单独作为一个配置类进行单独的组装。
@Component @ConfigurationProperties(prefix="px", ignoreInvalidFields=true, ignoreUnknownFields=true) public class MyAppConfiguration { static Logger log = LoggerFactory.getLogger(MyAppConfiguration.class); private Map<String, String> mysapps = new HashMap<String, String>(); public Map<String, String> getMyapps() { return myapps; } public void setMyapps(Map<String, String> myapps) { this.myapps = myapps; } }
3、List读取
(1)yml
myapps: - 1131f78c313e11e79da3000c298bdf0e: AMS系统 - 1ae211c543a14cf6981274fec3281f0c: BMS系统 - app1: 测试
(2)配置类写法
@Component @ConfigurationProperties(prefix="px", ignoreInvalidFields=true, ignoreUnknownFields=true) public class MyAppConfiguration { static Logger log = LoggerFactory.getLogger(MyAppConfiguration.class); private List<Map<String, String>> mysapps = new ArrayList<Map<String, String>>(); public List<Map<String, String>> getMyapps() { return myapps; } public void setMyapps(List<Map<String, String>> myapps) { this.myapps = myapps; } }
4、问题:配置类没有获取到值
该问题的原因很可能是yml中定义的key与配置类中定义的属性名称不一致,导致Springboot自动装配时失败。出现该问题后,一定首先要仔细检查配置类对应属性的名称以及配置类映射的路径。
Springboot yml内list、map组合写法
yml:
myProps: varmaplist: key11: - t1 - t2 - t3 key22: - t11 - t22 - t33 list: - topic1 - topic2 - topic3 maps: {key1: 'value1', key2: 'value2'}
MyProps:
@Component @Data @Configuration @PropertySource(value = {"classpath:/bootstrap.yml"}, encoding = "utf-8") @ConfigurationProperties(prefix = "myProps") public class MyProps { private List<String> list; private Map<String,String> maps; private Map<String,List<String>> varmaplist; }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容