2

I have a custom implementation of org.springframework.beans.factory.FactoryBean spring interface. If I create its instance and register it as a bean, then it's getting registered by spring and I can use values produced by it, as expected:

@Bean
public FactoryBean<T> create() {
     return new CustomFactoryBean();
}

However, I have a property, that is a list of strings and for each string I want to create a separate FactoryBean instance, then I want to autowire a collection of values where each value is generated by a separate FactoryBean. Is there a way to do that?

Ideally I want to do something like that:

@Bean
public Collection<FactoryBean<T>> createMultiple(@Value("${someproperty}") Set<String> values) {
     return values.stream().map(s -> new CustomFactoryBean(s)).collect(toList());
}

@Bean
public SomeService createService(Collection<T> createdValues) { //every value is produced by a separate factory
     return new SomeService(createdValues);
}

The code above unfortunately doesn't work, it just registeres a bean that is a collection of instances of a FactoryBean, but doesn't register factories...

Ruslan Akhundov
  • 2,178
  • 4
  • 20
  • 38

1 Answers1

0

You need to create a BeanDefinitionBuilder and programmatically registered all the factory beans into application context inside createMultiple method.

BeanDefinitionRegistry registry passed as parameterand use
registry.registerBeanDefinition(beanName, builder.getBeanDefinition());

Reference : Spring - Programmatically generate a set of beans

Ravi Sharma
  • 160
  • 4