|
对于最新稳定版本,请使用Spring AMQP 4.0.0! |
元注释
有时你可能想为多个监听者使用相同的配置。为了减少模板配置,你可以使用元注释创建自己的监听者注释。以下示例展示了如何实现:
@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支持以覆盖元注释的属性。此外,用户注释现在可以@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();
}