Meta-annotations

有時您可能想要對多個監聽器使用相同的組態。為了減少重複設定,您可以使用 meta-annotations 來建立您自己的監聽器註解。以下範例說明如何執行此操作

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@RabbitListener(bindings = @QueueBinding(
        value = @Queue,
        exchange = @Exchange(value = "metaFanout", type = ExchangeTypes.FANOUT)))
public @interface MyAnonFanoutListener {
}

public class MetaListener {

    @MyAnonFanoutListener
    public void handle1(String foo) {
        ...
    }

    @MyAnonFanoutListener
    public void handle2(String foo) {
        ...
    }

}

在先前的範例中,由 @MyAnonFanoutListener 註解建立的每個監聽器都會將匿名、自動刪除的佇列繫結至 fanout 交換器 metaFanout。從 2.2.3 版開始,支援 @AliasFor 以允許覆寫 meta-annotated 註解上的屬性。此外,使用者註解現在可以是 @Repeatable,允許為方法建立多個容器。

@Component
static class MetaAnnotationTestBean {

    @MyListener("queue1")
    @MyListener("queue2")
    public void handleIt(String body) {
    }

}


@RabbitListener
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MyListeners.class)
static @interface MyListener {

    @AliasFor(annotation = RabbitListener.class, attribute = "queues")
    String[] value() default {};

}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
static @interface MyListeners {

    MyListener[] value();

}