【问题标题】:Spring Boot @ConfigurationProperties - getting all property keys programmatically?Spring Boot @ConfigurationProperties - 以编程方式获取所有属性键?
【发布时间】:2017-06-06 05:50:30
【问题描述】:
我正在使用 Spring Boot 1.4.3 和新的类型安全属性。目前我已经成功/自动将多个属性(例如my.nested.thing1)映射到如下类:
@ConfigurationProperties(prefix="my")
public class My {
Nested nested = new Nested();
public static class Nested {
String thing1;
String thing2;
//getters and setters....
}
}
我的问题是,如何以编程方式列出 @ConfigurationProperties 类中的所有可能属性?类似于 Spring 在https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html 中列出所有常见属性的方式。我想打印:
my.nested.thing1
my.nested.thing2
现在我正在手动维护一个列表,但这使得我们在更改或添加属性时变得非常困难。
【问题讨论】:
标签:
spring
spring-boot
properties
【解决方案1】:
在翻阅 Spring Boot 源代码后想通了:
@PostConstruct
public void printTheProperties() {
String prefix = AnnotationUtils.findAnnotation(My.class, ConfigurationProperties.class).prefix();
System.out.println(getProperties(My.class, prefix));
}
/**
* Inspect an object recursively and return the dot separated property paths.
* Inspired by org.springframework.boot.bind.PropertiesConfigurationFactory.getNames()
*/
private Set<String> getProperties(Class target, String prefix) {
Set<String> names = new LinkedHashSet<String>();
if (target == null) {
return names;
}
if (prefix == null) {
prefix = "" ;
}
PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(target);
for (PropertyDescriptor descriptor : descriptors) {
String name = descriptor.getName();
if (name.equals("class")) {
continue;
}
if (BeanUtils.isSimpleProperty(descriptor.getPropertyType())) {
names.add(prefix + "." + name);
} else {
//recurse my pretty, RECURSE!
Set<String> recursiveNames = getProperties(descriptor.getPropertyType(), prefix + "." + name);
names.addAll(recursiveNames);
}
}
return names;
}