28 окт. 2011 г.

Spring Boostrap

We uses spring framework within each our project. I would like to share some small and useful tricks we use in our Bootstrap class.

To load any xml spring context you have to run smth like

try {
    final ClassPathXmlApplicationContext ctx = 
        new ClassPathXmlApplicationContext(
            new String[] {"application-context.xml"});
} catch ( final Throwable th) {
    log.error("Unable to start the context : " + th.getMessage(), th);
}

It's enough in the most cases.

For sure - it should be one main class in the whole project or several.

As well it would be better to add some more functionality there :
  • ctx.registerShutdownHook() - close context & releasing all resources on jvm shutdown
  • log4j (or what do you prefer to use?) initialization - just org.apache.log4j.BasicConfigurator.configure() call.
  • set the default java.lang.Thread.UncaughtExceptionHandler - it helps if some thread dies occasionally - at least you have a chance to log the exception for further investigation of the root cause - otherwise, thread will die peacefully and silent.
  • addBeanPostProcessor instance at createBeanFactory method. It handles bean initialization phase:
    • just before bean start
      • to be sure where is the bean's class source location - just from properly packed jar-file or some hot-fix bypass.
      • start timeout watchdog - if some start time of bean exceeding the reasonable threshold (e.g. 1 minute) and initialization hasn't been finished yet - put a warning message to have an earlier issue detection - probably the bean depends on some external system (as database) that unavailable at the moment of start.
    • after initialization - put a bean start up time log message into dedicated context log file
  • watchdog for application start time during some reasonable time (let's say 10 minutes)
  • put the total app start time into context log file

Комментариев нет: