0

I want create a RabbitListener when a property is present, but @ConditionOnProperty cannot combine with @RabbitListener. Now I have a workaround below. Does it exist any better method?

@Bean
@ConditionalOnProperty(name = "pmc.multiple.hypervisor.reply.routerkey.kvm")
public SimpleMessageListenerContainer kvmReplyQueueConsumer() {
    return getSimpleMessageListenerContainer(environment
            .getProperty("pmc.multiple.hypervisor.reply.routerkey.kvm"));
} 
Gary Russell
  • 166,535
  • 14
  • 146
  • 179
GrapeBaBa
  • 1,391
  • 3
  • 12
  • 22

2 Answers2

3

Did you actually try it? This works fine for me...

public static class ConditionalListener {

    @RabbitListener(queues="test.queue")
    public void listen(String foo) {
        System.out.println(foo);
    }

}

@ConditionalOnProperty("foo.enabled")
@Bean
public ConditionalListener foo() {
    return new ConditionalListener();
}

When run with -Dfoo.enabled=true I get messages; otherwise the bean is not declared.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
  • thanks, gary. actually my condition is the queue wether exist, the property is the queue name. in your code, when you say the bean not declare, does the simplemessagelistenercontainer not been created? – GrapeBaBa Oct 21 '15 at 14:12
  • Correct, the bean is not declared, so no container is created - but this is a static property - you can't make it conditional on whether a queue exists in rabbitmq only on whether the property is present. In order to do that, allow the container to be created, but with `autoStartup=false` and then start the container in your code if the queue is present. – Gary Russell Oct 21 '15 at 14:24
0

you can using @Component and @Conditional for a single class

zhaoxj
  • 1