如何在春季配置中创建NewTopic bean列表?

时间:2019-03-22 13:43:39

标签: spring spring-boot dependency-injection spring-kafka

我在yaml文件中配置了10个kafka主题,我需要在应用开始时创建所有主题。但是我不明白如何使用List。我可以创建一个bean:

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

但是现在我有了列表配置:

@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?
    }

}

2 个答案:

答案 0 :(得分:0)

  1. 您需要实现ContextCustomizer
  2. 获取ConfigurableListableBeanFactory的引用
  3. 并手动调用ConfigurableListableBeanFactory.initializeBean()
  4. 和ConfigurableListableBeanFactory.registerSingleton()

我认为通过经典的弹簧注释没有简单的方法。

您可以从Context hierarchy in Spring Boot based tests

获取起点

答案 1 :(得分:0)

您应该定义自定义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;
    }
}