我使用的是Spring Boot 1.4.3和新的类型安全属性。目前,我已将Spring成功/自动映射到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
现在我手动维护一个列表但是每当我们更改或添加属性时都会非常困难。
答案 0 :(得分:0)
在挖掘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;
}