Я создаю Spring beans динамически (используя метод, описанный в: 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 с моим 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;
}
тогда вы можете использовать buildProperties (configurableEnvironment) в своем beanPostProcessor.
Для Spring Boot версии 2. + вы должны использовать реорганизованный API привязки.