我在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?
}
}
答案 0 :(得分:0)
我认为通过经典的弹簧注释没有简单的方法。
获取起点答案 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;
}
}