How to create an Object from an Bean Definition in Spring 4?

2.6k views Asked by At

I have a method with return type 'AbstractBeanDefinition', this method is supposed to set all the necessary properties and return it.

    public AbstractBeanDefinition constructJMSMessage() {

    BeanDefinitionBuilder theMessagingService =  BeanDefinitionBuilder.rootBeanDefinition(MessagingService.class);
    theMessagingService.addPropertyValue(..);
    theMessagingService.addPropertyValue(..);
    theMessagingService.addPropertyValue(..);

    return theMessagingService.getBeanDefinition()

}

In the caller place, i want to create a object based on the bean defintion returned by this method. How can i do that ?

   public void ConstructIt()
  {
     MessagingService obj = constructJMSMessage();
  }
1

There are 1 answers

0
pingw33n On

You need to register BeanDefinition with the BeanDefinitionRegistry (with is usually a DefaultListableBeanFactory instance) first and then use it as a regular bean.

FileSystemXmlApplicationContext c = new FileSystemXmlApplicationContext();
c.refresh();

BeanDefinitionRegistry bdr = (BeanDefinitionRegistry) c.getBeanFactory();
BeanDefinitionBuilder bdb = BeanDefinitionBuilder.genericBeanDefinition(String.class)
        .addConstructorArgValue("test");
BeanDefinition bd = bdb.getBeanDefinition();
bdr.registerBeanDefinition("testBean", bd);

String tb = c.getBean("testBean", String.class);