Close

Spring Framework - ApplicationListener Examples

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;

@Configuration
public 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);
}
}
}
Original Post




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;

@Configuration
public 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);
}
}
}
Original Post




See Also