Sometimes we are working on an application where we have no control over specific Spring bean implementations. Nevertheless we want to check for the existence (or duplication) of these bean implementations during start-up of the application server. Since Spring version 3.0 it is possible to use Spring's ApplicationListener. This interface is based on the EventListener and uses the standard Observer design pattern. In 3 steps we can easily check for the existence of a specific Spring bean.

  1. We create an ApplicationListener<ContextRefreshedEvent> implementation. The method onApplicationEvent will be called when a refresh of the ApplicationContext occurs.

    package com.jdriven.blog.applicationlistener;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationListener;
    import org.springframework.context.event.ContextRefreshedEvent;
    
    public class BeanContextStartupListener
       implements ApplicationListener<ContextRefreshedEvent>
    {
       public void onApplicationEvent( ContextRefreshedEvent event )
       {
          ...
       }
    }
    
  2. We need to register the BeanContextStartupListener as a Spring Component. In this sample we just simply enable component scanning in the spring xml configuration as follows.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:component-scan base-package="com.jdriven.blog.applicationlistener" />
    </beans>
    

    We also add the @Component to the class definition:

    import org.springframework.stereotype.Component;
    
    @Component
    public class BeanContextStartupListener
       implements ApplicationListener<ContextRefreshedEvent>
    
  3. We implement the onApplicationEvent method of the BeanContextStartupListener and throw an Exception when no bean exists within the current ApplicationContext.

    public void onApplicationEvent( ContextRefreshedEvent event )
    {
       Map serviceImplementations = event.getApplicationContext().getBeansOfType( JDrivenService.class );
       if ( serviceImplementations.isEmpty() ) {
          throw new IllegalStateException("JDrivenService was not instantiated during startup.");
       }
    }
    

As mentioned before we can also check for the occurance of Beans with a certain interface. For example: We need to check if there is only one implementation of the JDrivenEmailService and throw a specific Exception when there isn't.

shadow-left