元注解

有时你可能想要对多个监听器使用相同的配置。为了减少样板配置,你可以使用元注解来创建你自己的监听器注解。下面的示例展示了如何做到这一点

@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();

}