元注解
有时,您可能希望将相同的配置用于多个监听器。为了减少样板配置,您可以使用元注解创建自己的监听器注解。以下示例展示了如何实现:
@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();
}