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();
beanDefinition.setBeanClass(String.class);
beanDefinition.setLazyInit(false);
beanDefinition.setAbstract(false);
beanDefinition.setAutowireCandidate(true);
ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues();
beanDefinition.setConstructorArgumentValues(constructorArgumentValues);
constructorArgumentValues.addIndexedArgumentValue(0, beanValue, "java.lang.String");
beanDefinition.setConstructorArgumentValues(constructorArgumentValues);
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.