我有这个spring-cloud-config客户端类,我可以使用@Value注释来访问各个属性.但是,我有兴趣知道如何从属性文件中读取所有属性值,而不将每个属性的键绑定到@Value注释.基本上我的想法是,我想从属性文件中读取所有属性值,甚至不知道文件中定义的属性.知道我怎么能这样做吗?
客户类
@EnableautoConfiguration @ComponentScan @RestController @RefreshScope public class ConfigDemoClIEntApplication { @Value("${special}") String special; @RequestMapPing("/restaurant") public String hello() { return "Hello " + special; } public static voID main(String[] args) { SpringApplication.run(ConfigDemoClIEntApplication.class,args); }}
示例属性文件
special: bargain! amount: 200 city: New York
在这个例子中,我想读取所有3个属性,而不是在我的类中为每个属性定义@Value注释.那可能吗?
谢谢你的帮助.
最佳答案我刚刚解决了你创建这个applicationProps bean的问题,这是一个包含应用程序所有属性的java.util.PropertIEs对象.唯一需要考虑的是自动装配的Environment对象.
这是代码:
@autowired Environment env; //Load all the propertIEs of the server and put them into a java PropertIEs obj @Bean(name = "applicationProps") public PropertIEs applicationPropertIEs() { final PropertIEs propertIEs = new PropertIEs(); for(Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator(); it.hasNext(); ) { PropertySource propertySource = (PropertySource) it.next(); if (propertySource instanceof PropertIEsPropertySource) { log.info("Adding all propertIEs contained in " + propertySource.getname()); propertIEs.putAll(((MapPropertySource) propertySource).getSource()); } if (propertySource instanceof CompositePropertySource){ propertIEs.putAll(getPropertIEsInCompositePropertySource((CompositePropertySource) propertySource)); } } return propertIEs; } private PropertIEs getPropertIEsInCompositePropertySource(CompositePropertySource compositePropertySource){ final PropertIEs propertIEs = new PropertIEs(); compositePropertySource.getPropertySources().forEach(propertySource -> { if (propertySource instanceof MapPropertySource) { log.info("Adding all propertIEs contained in " + propertySource.getname()); propertIEs.putAll(((MapPropertySource) propertySource).getSource()); } if (propertySource instanceof CompositePropertySource) propertIEs.putAll(getPropertIEsInCompositePropertySource((CompositePropertySource) propertySource)); }); return propertIEs; } @autowired @QualifIEr("applicationProps") PropertIEs applicationPropertIEs;
需要getPropertIEsInCompositePropertySource方法中的递归步骤,因为从配置服务器获取的属性以递归方式嵌套在CompositePropertySource中
希望能帮助到你
问候
总结以上是内存溢出为你收集整理的如何从Spring-cloud-config客户端的源属性文件中读取所有属性值全部内容,希望文章能够帮你解决如何从Spring-cloud-config客户端的源属性文件中读取所有属性值所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)