Wednesday, October 2, 2013

Spring: Force a bean to be the first to initialize

Spring provides the "depends-on" bean attribute to control bean initialization order.  Unfortunately, there are some rare cases where you really want to run some code before the application context initializes.  An example scenario might involve messing around with the thread class loader before something like "PropertiesPlaceholderConfigurer" has a chance to initialize.

There are a number of ways to go about this, but the easiest might be through implementing a PriorityOrdered BeanFactoryPostProcessor.  After all spring beans are defined, spring calls all BeanFactoryPostProcessor s defined in the application context.  Post processors that implement PriorityOrdered, and have the highest precedence are called first.

To execute some code before any other spring beans or processors have a chance to initialize, one can therefore use something like the following:
        
/**
 * An example spring pre-initializer.  Referncing this class as a bean in an 
 * application context will cause it to be the first executed PostProcessor 
 * after all beans in the application context are defined.
 */
public class PreInitializer implements BeanFactoryPostProcessor, PriorityOrdered {
 @Override
 public int getOrder() {
  return Ordered.HIGHEST_PRECEDENCE;
 }
 @Override
 public void postProcessBeanFactory(
   ConfigurableListableBeanFactory beanFactory) throws BeansException {
  /* put initialization code here */
 }
}

This is an easy hack to perform initialization tasks that might affect the application context before anything else - including property resolution has a chance to run.

1 comment: