Meta-annotations

有时,您可能希望为多个监听器使用相同的配置。为了减少重复的配置代码,您可以使用元注解来创建自己的监听器注解。以下示例展示了如何实现这一点:spring-doc.cadn.net.cn

@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,从而允许为一个方法创建多个容器。spring-doc.cadn.net.cn

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

}