Spring ApplicationListener and Events

Spring ApplicationListener

Spring has an implementation of an ApplicationListener that allows Spring projects to fire useful events for those interested (Observer Pattern, see Spring Doc). To gain access to these events all you need is a bean in the Application Context that implements ApplicationListener. If you opt to just use the base class then you will get every supported event. In Spring 3 you can specifically define the desired event and no extra logic is needed to filter events.

The code below will catch any ApplicationEvent fired by Spring. With this style it’s up to us to filter the events and process them accordingly. Based on the implemented Spring packages the events capabilities will vary.

@Component
public class MyAppListener implements ApplicationListener<ApplicationEvent> {

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {

        // process event
        if(applicationEvent instanceof ContextRefreshedEvent)
        {
            // fire ping to statsd server
        } 
        else if (applicationEvent instanceof ServletRequestHandledEvent)
        {
            // fire ping to statsd server    
        }
    }
}

The alternative to the above example is to specifically declare the event we want. Spring 3 recognizes the type in the generic declaration and will only send what we want.

@Component
public class MyAppListener implements ApplicationListener<AuthenticationSuccessEvent> {

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent applicationEvent) {

        // We have a successful login, track the event, clear the failed login count
    }
}

Here are some events you can listen for. The Spring documents have more info on specific events.

  • Core events are available (ContextClosedEvent, ContextRefreshedEvent, ContextStartedEvent, ContextStoppedEvent)
  • Web events (PortletRequestHandledEvent, ServletRequestHandledEvent)
  • Security has a lot of events with every type of failure (AuthenticationFailureBadCredentialsEvent, AuthenticationFailureCredentialsExpiredEvent…) and non failure events (AuthenticationSuccessEvent, AuthenticationSwitchUserEvent, InteractiveAuthenticationSuccessEvent)

The Security events are useful to fire off logging, graphing or reporting pings. It can also be used to track failed login attempts across multiple entry points. The alternative is to add logic into a Success or Failed handler in the security context but this is a nice separation and a central location. Just be sure to document! it can be hard to see what happens in events when following code in the IDE.

By default these events are not asynchronous.

Leave a Reply

Your email address will not be published. Required fields are marked *