如何在springboot里,使用Environment 读取所有application.yml里某一层级下所有的内容
时间: 2024-02-26 14:56:57 浏览: 13
可以使用`Environment`的`getPropertySources()`方法获取所有的属性源,然后遍历属性源获取所有的属性值。具体实现可以参考以下代码:
```java
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import java.util.HashMap;
import java.util.Map;
public class ApplicationPropertiesReader {
private final Environment environment;
public ApplicationPropertiesReader(Environment environment) {
this.environment = environment;
}
public Map<String, Object> readProperties(String prefix) {
Map<String, Object> properties = new HashMap<>();
for (PropertySource<?> propertySource : environment.getPropertySources()) {
if (propertySource.getSource() instanceof Map) {
Map<String, Object> propertyValues = Binder.get(environment).bind(prefix, Map.class).get();
properties.putAll(propertyValues);
}
}
return properties;
}
}
```
这个类提供了一个`readProperties`方法,可以根据传入的`prefix`读取所有的属性值。例如,如果你想读取所有以`app`为前缀的属性值,可以这样调用:
```java
Map<String, Object> properties = new ApplicationPropertiesReader(environment).readProperties("app");
```
这将返回一个`Map`,其中包含所有以`app`为前缀的属性值。