我有这个 spring-cloud-config 客户端类,我可以使用 @Value 注释访问各个属性就好了。但是,我很想知道如何从属性文件中读取所有属性值,而不将每个属性的键绑定(bind)到 @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 个属性,而不为我的类(class)中的每个属性定义 @Value 注释。那可能吗?
谢谢你的帮助。
最佳答案
我刚刚解决了创建这个 applicationProps bean 的问题,它是一个包含应用程序所有属性的 java.util.Properties 对象。
唯一需要的是一个 Autowiring 的环境对象。
这是代码:
@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 - 如何从 Spring-cloud-config 客户端中的源属性文件中读取所有属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38035340/