我如何扩展 spring-kafka 的“@KafkaListener”注释来创建我自己的具有有限属性的注释?

How can i extend spring-kafka's '@KafkaListener' annotation to create my own annotation with limited attributes?

我一直在方法级别使用“@KafkaListener”来创建消费者。现在,我正在尝试通过扩展 '@KafkaListener' 并限制属性的数量来创建自己的自定义注释(例如,由于某些原因,我不想公开像 'errorHandler' [=14 这样的属性=] 等)。现在我的问题是,要实现这一点,是否有扩展现有 '@KafkaListener' 的选项?请提出建议。

是的,这很容易。

@SpringBootApplication
public class So61684460Application {

    public static void main(String[] args) {
        SpringApplication.run(So61684460Application.class, args);
    }

    @MyListener(topics = "so61684460", id = "so61684460")
    public void listen(String in) {
        System.out.println(in);
    }

    @Bean
    public NewTopic topic() {
        return TopicBuilder.name("so61684460").partitions(3).replicas(1).build();
    }

}

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@KafkaListener(concurrency = "${my.concurrency}")
@interface MyListener {

    @AliasFor(annotation = KafkaListener.class, attribute = "id")
    String id();

    @AliasFor(annotation = KafkaListener.class, attribute = "topics")
    String[] topics() default "";

}

如您所见,除了限制某些属性的可见性外,您还可以将它们设为必需(id 以上),更改默认值,或在不可见的设置中设置硬编码或参数化值属性(上面的concurrency)。

这是描述in the documentation