我有这个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对象.
原文链接:https://www.f2er.com/spring/432379.html唯一需要考虑的是自动装配的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中
希望能帮助到你
问候