Categories
Uncategorized

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");
  main.run();

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();
  context.addBeanFactoryPostProcessor(ppc);
  context.setConfigLocation("context.xml");
  context.refresh();

  Main main = (Main) context.getBean("main");
  main.run();

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

One reply on “Bootstrapping Spring”

Leave a Reply to Winter Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s