Search code examples
javaspring-bootspring-cloudkafka-consumer-apievent-listener

How to run consumer @StreamListener only after ApplicationReadyEvent method completed?


I have a consumer method with

@StreamListener(target = Sink.INPUT)
method()

And I have a method with an event listener

@EventListener(ApplicationReadyEvent.class)
method()...

Is it possible to configure @StreamListener to start listening only after @EventListener method is completed?


Solution

  • According to Spring Cloud Stream docs you could use property spring.cloud.stream.bindings.<bindingName>.consumer.autoStartup=false which will stop BindingService from automatically starting consumer binding. Then you can do it yourself whenever you need, e.g. in ApplicationReadyEvent listener.

    public class DelayedBindingStarter {
    
        private final BindingsEndpoint bindingsEndpoint;
    
        @EventListener(ApplicationReadyEvent.class)
        public void applicationReady() {
            bindingsEndpoint.changeState("binding_name", BindingsLifecycleController.State.STARTED);
        }
    }