从org.springframework.core.env.PropertySource一次使用BeanDefinitionRegistryPostProcessor加载配置POJO

问题描述 投票:0回答:1

我动态创建弹簧豆(使用方法描述在: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
                }
            }
        }
    }

我的问题就是为此,有没有一种方法,而无需手动迭代与这些PropertySources我的POJO映射?

java spring spring-boot pojo
1个回答
1
投票

我有一个丑陋的方式...

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

© www.soinside.com 2019 - 2024. All rights reserved.