You cannot create @KafkaListener
s programmatically, only discrete listener containers (with a custom listener).
You can do it by programmatically creating a child application context for each listener.
EDIT
@SpringBootApplication
public class So53715268Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(So53715268Application.class, args);
for (int i = 0; i < 2; i++) {
AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext();
child.setParent(context);
child.register(ChildConfig.class);
Properties props = new Properties();
props.setProperty("group", "group." + i);
props.setProperty("topic", "topic" + i);
PropertiesPropertySource pps = new PropertiesPropertySource("listenerProps", props);
child.getEnvironment().getPropertySources().addLast(pps);
child.refresh();
}
}
}
and
@Configuration
@EnableKafka
public class ChildConfig {
@Bean
public Listener listener() {
return new Listener();
}
}
and
public class Listener {
@KafkaListener(id = "${group}", topics = "${topic}")
public void listen(String in) {
System.out.println(in);
}
}
and
: partitions assigned: [topic0-0]
: partitions assigned: [topic1-0]
Note that, if you are using Spring Boot, the child config class and listener must be in a different package to the main app (and not a sub-package either).