brai
brai

Reputation: 55

ContextRefreshedEvent is invoking every time instead of ContextStartedEvent

I am trying ApplicationListener but I get a ContextRefreshedEvent invoked every time. I want to know when ContextStartedEvent is invoked.

public class CustomListener implements ApplicationListener{

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
       if(applicationEvent instanceof ContextRefreshedEvent){
           System.out.println("<><><>refresh event......");
       }else if(applicationEvent instanceof ContextStartedEvent){
            System.out.println("<><><><>started event......");
       }else{
           System.out.println("......else........");
       }
    }

}

Upvotes: 1

Views: 5281

Answers (2)

mhasan
mhasan

Reputation: 3709

ContextStartedEvent is published when you explicitly invoke ConfigurableAppicationContext.start() on the context

ContextRefreshedEvent may be published more than once, and therefore it may be also published before all the beans are initialized

start() is a method of Lifecycle interface which is extended by ConfigurableApplicationContext and explicitly implemented by org.springframework.context.support.AbstractApplicationContext.It is mainly used to support asynchronous processing

Distinction between start and refresh is that:

refresh is usually called implicitly during creation of concrete ApplicationContext, so we (developers) are more used to it.

start is always explicit So - if you want to get ContextStartedEvent, you should call start() on ApplicationContext.

Upvotes: 2

Related Questions