Tuesday 23 February 2010

Dynamically create spring bean

I used this in a dbunit test to create a dummy service layer bean dynamically.

The rest of the beans were configured in xml files. I created this bean dynamically in the test so that I didn't have to pollute the xml config.

// Dynamically create a DummyServiceToMakeCodeTransactional bean and register with spring
     DefaultListableBeanFactory autowireCapableBeanFactory = (DefaultListableBeanFactory) getApplicationContext().getAutowireCapableBeanFactory();
     AbstractBeanDefinition beanDefinition =
          BeanDefinitionBuilder.rootBeanDefinition(
               DummyServiceToMakeCodeTransactional.class.getName()).getBeanDefinition();
     autowireCapableBeanFactory.registerBeanDefinition("DummyService", beanDefinition);
     DummyServiceToMakeCodeTransactional bean = (DummyServiceToMakeCodeTransactional) 
     getApplicationContext().getBean("DummyService");

No comments: