java - 使用 BeanDefinitionRegistryPostProcessor 从 org.springframework.core.env.PropertySource 加载配置 POJO

标签 java spring spring-boot pojo

我正在动态创建 spring bean(使用: 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 {

并 Autowiring 到 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 映射到我的 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)。

对于 Spring Boot 版本 2.+,您必须使用 refactored binding API .

关于java - 使用 BeanDefinitionRegistryPostProcessor 从 org.springframework.core.env.PropertySource 加载配置 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51163251/

相关文章:

java.lang.NumberFormatException : For input string: "2017-01-28 13:28:20" 异常

java - CRUDRepository 中的 Update 或 saveorUpdate

java - x509认证失败时重定向循环

mysql - Spring Boot 服务未连接到 GKE 的 kubernetes 内的 mysql DB 服务

java - Android - 后退按钮导致问题

java - JTextPane 属性集

java - 在wildfly 11内的其他WAR中动态加载类

java - 在测试环境中使用 MariaDB,在生产环境中使用 sql server,如何同时使用一个选择? - Java, Spring

java - 为什么添加父类(super class)会破坏我的 Spring bean?

java - Spring-Boot 的最终目标