Spring Tip: Check for existence of Bean during startup

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.
  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.

    We also add the @Component to the class definition:
  3. We implement the onApplicationEvent method of the BeanContextStartupListener and throw an Exception when no bean exists within the current ApplicationContext.

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.

One thought on “Spring Tip: Check for existence of Bean during startup

  1. Actually the ApplicationListener can be used since springs inception and isn’t new in Spring 3.x. So basically it works in any spring version (although older version require a explicit check for the type of event due to the lack of generics).

Leave a Reply

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