Home > Spring > Programmatically defining spring bean

Programmatically defining spring bean

One one of my recent side projects, I needed to define a set of Spring Beans programatically using a BeanFactoryPostProcessor. Most of the posts online talked about using RootBeanDefinition class. In Spring API, I came across GenericBeanDefinition class that provides an convenient way for bean definitions.

Here is a code sinppet that defines a bean of type String:

      String beanName = "testBean";
      String beanValue= "testing";

      GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
      ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues();
            constructorArgumentValues.addIndexedArgumentValue(0, beanValue, "java.lang.String");
            registry.registerBeanDefinition(beanName, beanDefinition);  

If you don’t provide the type (java.lang.String here) as one of the parameters in your ArgumentValue and deploy it as part of a web application, you will run in to wierd propertyeditor issues.

Categories: Spring Tags:
  1. No comments yet.
  1. No trackbacks yet.