【问题标题】:How can I create list of NewTopic beans in spring configuration?如何在 Spring 配置中创建 NewTopic bean 列表?
【发布时间】:2019-03-22 13:43:38
【问题描述】:

我在我的 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?
    }

}

【问题讨论】:

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


    【解决方案1】:
    1. 您需要实现 ContextCustomizer
    2. 获取 ConfigurableListableBeanFactory 的引用
    3. 并手动调用ConfigurableListableBeanFactory.initializeBean()
    4. 和 ConfigurableListableBeanFactory.registerSingleton()

    我认为通过经典的 spring 注释没有任何简单的方法..

    您可以从Context hierarchy in Spring Boot based tests获取起点

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-25
        • 1970-01-01
        • 2022-08-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多