Search code examples
rabbitmqspring-amqpspring-rabbit

Can @RabbitListener apply by condition


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"));
} 

Solution

  • 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.