0

I configure 10 kafka topics in my yaml file and I need create all topics on aplication start. But I do not understand how can I do it with List. I can Create one bean:

@Bean
public NewTopic newTopic() {
    return new NewTopic("topic-name", 5, (short) 1);
}

But now I have list configs:

@PostConstruct
public void init(){
    Map<String, TopicProperties.Topic> topics = this.topics.getTopics();
    for (Map.Entry<String, TopicProperties.Topic> topicEntry : topics.entrySet()) {

        TopicProperties.Topic topic = topicEntry.getValue();

        String topicName = topic.getTopicName();
        int partitions = topic.getNumPartitions();
        short replicationFactor = topic.getReplicationFactor();

        //how can I create new bean of NewTopic?
    }

}
ip696
  • 6,574
  • 12
  • 65
  • 128

2 Answers2

0
  1. You need to implement ContextCustomizer
  2. Get a reference of ConfigurableListableBeanFactory
  3. and manually call ConfigurableListableBeanFactory.initializeBean()
  4. and ConfigurableListableBeanFactory.registerSingleton()

I do not think there is any easy way via classic spring annotations..

You can get a starting point from Context hierarchy in Spring Boot based tests

Vassilis
  • 914
  • 8
  • 23
0

You should define custom BeanDefinitionRegistryPostProcessor:

@Configuration
public class TopicsConfiguration {

    List<Topic> topics = ...

    @Bean
    public BeanDefinitionRegistryPostProcessor topicBeanDefinitionRegistryPostProcessor() {
        return new BeanDefinitionRegistryPostProcessor() {
            @Override
            public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
                topics.forEach(topic -> beanDefinitionRegistry.registerBeanDefinition("Topic" + topic.getName(), createTopicBeanDefinition(topic)));
            }

            @Override
            public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
            }
        };
    }

    private static BeanDefinition createTopicBeanDefinition(Topic topic) {
        GenericBeanDefinition bd = new GenericBeanDefinition();
        bd.setBeanClass(TopicBean.class);
        bd.getPropertyValues().add("name", topic.getName());

        return bd;
    }
}

StasKolodyuk
  • 4,256
  • 2
  • 32
  • 41