gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:03:23 25 4
gpt4 key购买 nike

我正在动态创建 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com