I have a Spring MVC application trying to use a rich domain model, with the following mapping in the Controller class:
@RequestMapping(value = "/entity", method = RequestMethod.POST)
public String create(@Valid Entity entity, BindingResult result, ModelMap modelMap) {
if (entity== null) throw new IllegalArgumentException("An entity is required");
if (result.hasErrors()) {
modelMap.addAttribute("entity", entity);
return "entity/create";
}
entity.persist();
return "redirect:/entity/" + entity.getId();
}
Before this method gets executed, Spring uses BeanUtils to instantiate a new Entity and populate its fields. It uses this:
...
ReflectionUtils.makeAccessible(ctor);
return ctor.newInstance(args);
Here's the problem:
My entities are Spring managed beans. The reason for this is to inject DAOs on them. Instead of calling new, I use EntityFactory.createEntity(). When they're retrieved from the database, I have an interceptor that overrides the
public Object instantiate(String entityName, EntityMode entityMode, Serializable id)
method and hooks the factories into that.
So the last piece of the puzzle missing here is how to force Spring to use the factory rather than its own BeanUtils reflective approach? Any suggestions for a clean solution?
Thanks very much in advance.