我动态创建弹簧豆(使用方法描述在:https://scanningpages.wordpress.com/2017/07/28/spring-dynamic-beans/)
@Configuration
class Conf {
@Bean
static BeanDefinitionRegistryPostProcessor beanPostProcessor(final ConfigurableEnvironment environment) {
...
}
但是不能通过常见的方式在POJO加载属性对象:
@Configuration
@ConfigurationProperties(prefix = "foo")
public class FooProperties {
并自动连接到beanPostProcessor
作为一个额外的参数(根本不起作用)。
现在我要重复这样的性质:
static private FooPorperties parseProperties(ConfigurableEnvironment environment) {
for(PropertySource source : environment.getPropertySources()) {
if(source instanceof EnumerablePropertySource) {
EnumerablePropertySource propertySource = (EnumerablePropertySource) source;
for(String property : propertySource.getPropertyNames()) {
if (property.startsWith("foo")) {
System.out.println(property);
// TODO set FooProperties
}
}
}
}
我的问题就是为此,有没有一种方法,而无需手动迭代与这些PropertySource
s我的POJO映射?
我有一个丑陋的方式...
public static FooProperties buildProperties(ConfigurableEnvironment environment) {
FooProperties fooProperties = new FooProperties();
if (environment != null) {
MutablePropertySources propertySources = environment.getPropertySources();
new RelaxedDataBinder(fooProperties, "foo").bind(new PropertySourcesPropertyValues(propertySources));
}
return fooProperties;
}
那么你可以使用你的BeanPostProcessor buildProperties(configurableEnvironment)。
春天引导版本2 +你必须使用refactored binding API。