Friday, February 23, 2018

Spring refresh: Standard Event Listeners


Spring has a easier way to handle context events. You just have to annotate a event handler method with @EventListener and accept the respect event class as the parameter. 

@Component
public class AppListener {

    Logger logger = Logger.getLogger(AppListener.class);

    @EventListener
    public void handleContextRefresh(ContextRefreshedEvent cfe) {
        logger.info("-- Context Refreshed at : " + new Date(cfe.getTimestamp()).toString());
    }

    @EventListener
    public void handleContextStarted(ContextStartedEvent cfe) {
        logger.info("-- Context Started at : " + new Date(cfe.getTimestamp()).toString());
    }
    @EventListener
    public void handleContextStop(ContextStoppedEvent cfe) {
        logger.info("-- Context Stopped at : " + new Date(cfe.getTimestamp()).toString());
    }
    @EventListener
    public void handleContextClose(ContextClosedEvent cfe) {
        logger.info("-- Context Closed at : " + new Date(cfe.getTimestamp()).toString());
    }
    @EventListener
    public void handleRequestHandle(RequestHandledEvent cfe) {
        logger.info("-- Request Handled at : " + new Date(cfe.getTimestamp()).toString());
    }

}


In the above code, context time events are logged in the console as and when it happens. 

For example. When the server is started or when you process the request, the following log appears. 
Context Close will be called while you shut down your application. 


-- Context Refreshed at : Sat Feb 24 00:57:14 CST 2018

Hibernate: insert into app_role (name, name_value) values (?, ?)
2018-02-24 01:01:05.465  INFO 50721 --- [nio-8080-exec-1] cs.trk.user.service.RoleService          : App role info modified : AppRole{id='20', name='User'}
2018-02-24 01:01:05.487  INFO 50721 --- [nio-8080-exec-1] cs.trk.user.config.AppListener           : -- Request Handled at : Sat Feb 24 01:01:05 CST 2018

2018-02-24 00:59:41.242  INFO 50425 --- [       Thread-4] cs.trk.user.config.AppListener           : -- Context Closed at : Sat Feb 24 00:59:41 CST 2018
2018-02-24 00:59:41.243  INFO 50425 --- [       Thread-4] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown


No comments:

Post a Comment