元註解

有時,您可能希望將相同的配置用於多個監聽器。為了減少樣板配置,您可以使用元註解建立自己的監聽器註解。以下示例展示瞭如何實現:

@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註解建立的監聽器都將一個匿名、自動刪除的佇列繫結到扇出交換器metaFanout。從版本2.2.3開始,支援@AliasFor,以允許覆蓋元註解上的屬性。此外,使用者註解現在可以是@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();

}
© . This site is unofficial and not affiliated with VMware.