Bootstrapping Spring

Recently, I’ve been converting a project to use Spring. My main method looks something like this.

  ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
  Main main = (Main) context.getBean("main");;

There’s a problem though. Several of my beans need to be configurable. Normally, I’d resolve this by using a PropertyPlaceholderConfigurer (or more likely the context:property-placeholder element). This lets me have values like ${baseDirectory} in my spring configuration.

But PropertyPlaceholderConfigurer takes a fixed location. I want that location to be specified on the command line.

This is something of a conundrum. But then I noticed the method addBeanFactoryPostProcessor() on ConfigurableApplicationContext. Now, I can make things work. This is what the code looks like now.

  PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
  ppc.setLocation(new FileSystemResource(args[0]));
  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
  Main main = (Main) context.getBean("main");;

Whilst it’s not as simple as before, it’s now hugely more flexible.