Spring Framework
Showing how to listen Spring built-in context related events by implementing ApplicationListener.
import org.springframework.context.ApplicationEvent;import org.springframework.context.ApplicationListener;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.event.ContextRefreshedEvent;@Configurationpublic class BuildInListenerBasedEventExample { @Bean AListenerBean listenerBean() { return new AListenerBean(); } public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( BuildInListenerBasedEventExample.class); } private static class AListenerBean implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { System.out.println("context refreshed event received: " + event); } }}
Using ApplicationListener to listen multiple events.
import org.springframework.context.ApplicationEvent;import org.springframework.context.ApplicationListener;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class BuildInListenerBasedMultipleEventExample { @Bean AListenerBean listenerBean () { return new AListenerBean(); } public static void main (String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( BuildInListenerBasedMultipleEventExample.class); context.stop(); context.start(); context.close(); } private static class AListenerBean implements ApplicationListener<ApplicationEvent> { @Override public void onApplicationEvent (ApplicationEvent event) { System.out.println("event received: "+event); } }}