Home > AI > Backend > SpringBoot >

Spring built-in events

Build-in EventDescription
ContextRefreshedEventEvent fired when an ApplicationContext gets initialized or refreshed (refreshed via context.refresh() call).
ContextStartedEventEvent fired when context.start() method is called.
ContextStoppedEventEvent fired when context.stop() method is called
ContextClosedEventEvent fired when context.close() method is called.
RequestHandledEventThis event can only be used in spring MVC environment. It is called just after an HTTP request is completed.

Example

@Configuration
 class BuildInAnnotationBasedEventExample {

    @Bean
    AListenerBean listenerBean() {
        return new AListenerBean();
    }

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(BuildInAnnotationBasedEventExample.class);
        System.out.println("-- refreshing context --");
        context.refresh();
        System.out.println("-- stopping context --");
        context.stop();
        System.out.println("-- starting context --");
        context.start();
        System.out.println("-- closing context --");
        context.close();
    }

    private static class AListenerBean {

        @EventListener
        public void handleContextRefreshed(ContextRefreshedEvent event) {
            System.out.println("context refreshed event received: " + event);
        }

        @EventListener
        public void handleContextStarted(ContextStartedEvent event) {
            System.out.println("context started event received: " + event);
        }

        @EventListener
        public void handleContextStopped(ContextStoppedEvent event) {
            System.out.println("context stopped event received: " + event);
        }

        @EventListener
        public void handleContextClosed(ContextClosedEvent event) {
            System.out.println("context closed event received: " + event);
        }
    }
}

Leave a Reply