Meta-annotations
有时,您可能希望对多个侦听器使用相同的配置。为减少样板配置,可以使用元注解创建自己的侦听器注解。以下示例演示了如何执行此操作:
Sometimes you may want to use the same configuration for multiple listeners. To reduce the boilerplate configuration, you can use meta-annotations to create your own listener annotation. The following example shows how to do so:
@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
,从而允许为方法创建多个容器。
In the preceding example, each listener created by the @MyAnonFanoutListener
annotation binds an anonymous, auto-delete
queue to the fanout exchange, metaFanout
.
Starting with version 2.2.3, @AliasFor
is supported to allow overriding properties on the meta-annotated annotation.
Also, user annotations can now be @Repeatable
, allowing multiple containers to be created for a method.
@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();
}