There are times when you would need to create an object through reflection and then call the invoke on all the setters of that object to set the attribute values. Doing this through java’s reflection is messy, and you would have to know whether the setter is of Date type (say) and convert it appropriately.
Spring provides 2 ways to deal with this:
1. Use DataBinder: Most of the stuff is mentioned in this blog, http://technology.amis.nl/blog/1619/using-the-spring-databinder-to-map-strings-to-objects, but in case the link gets broken in the future, the main chunk of the api would be something like this:
MutablePropertyValues values = new MutablePropertyValues();
values.addPropertyValue("id", "7839");
values.addPropertyValue("name", "KING");
values.addPropertyValue("department", "20");
Employee employee = new Employee();
DataBinder binder = new DataBinder(employee);
binder.bind(values);
2. I prefer this approach where I dont have to even create the original object using reflection (which is what one would have to do in the earlier approach).
GenericApplicationContext ctx = new GenericApplicationContext();
BeanDefinitionBuilder builderA = BeanDefinitionBuilder.rootBeanDefinition(BeanA.class).addPropertyValue("name", "Joe");
ctx.registerBeanDefinition("bean-a", builderA.getBeanDefinition());
BeanDefinitionBuilder builderB = BeanDefinitionBuilder.rootBeanDefinition(BeanB.class).addPropertyReference("refA", "bean-a");
ctx.registerBeanDefinition("bean-b", builderB.getBeanDefinition());
ctx.getBean("bean-b");
On the ctx object, one can then set custom editors if required (spring provides a lot of defaults so only when you want to be different or when spring doesn’t provide one, one would need to do this)