yathirigan
yathirigan

Reputation: 6069

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

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();
  }

Upvotes: 1

Views: 2846

Answers (1)

pingw33n
pingw33n

Reputation: 12510

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);

Upvotes: 3

Related Questions