@KafkaListener Attribute Modification

从 2.7.2 版开始,您现在可以在创建容器之前对注释属性进行编程方式的修改。要这样做,请向应用程序上下文中添加一个或多个 KafkaListenerAnnotationBeanPostProcessor.AnnotationEnhancerAnnotationEnhancer 是一个 BiFunction<Map<String, Object>, AnnotatedElement, Map<String, Object>,它必须返回一个属性映射。属性值可以包括 SpEL 和/或属性占位符;在执行任何解析之前调用增强器。如果有多个增强器,并且它们实现了 Ordered,那么将按顺序调用它们。

Starting with version 2.7.2, you can now programmatically modify annotation attributes before the container is created. To do so, add one or more KafkaListenerAnnotationBeanPostProcessor.AnnotationEnhancer to the application context. AnnotationEnhancer is a BiFunction<Map<String, Object>, AnnotatedElement, Map<String, Object> and must return a map of attributes. The attribute values can contain SpEL and/or property placeholders; the enhancer is called before any resolution is performed. If more than one enhancer is present, and they implement Ordered, they will be invoked in order.

必须在应用程序上下文的生命周期早期声明 AnnotationEnhancer bean 定义,因为它们非常必要。

AnnotationEnhancer bean definitions must be declared static because they are required very early in the application context’s lifecycle.

下面是一个示例:

An example follows:

@Bean
public static AnnotationEnhancer groupIdEnhancer() {
    return (attrs, element) -> {
        attrs.put("groupId", attrs.get("id") + "." + (element instanceof Class
                ? ((Class<?>) element).getSimpleName()
                : ((Method) element).getDeclaringClass().getSimpleName()
                        +  "." + ((Method) element).getName()));
        return attrs;
    };
}