Custom bean instantiation logic in Spring MVC

Posted by Michal Bachman on Stack Overflow See other posts from Stack Overflow or by Michal Bachman
Published on 2010-04-01T13:39:57Z Indexed on 2010/04/01 13:43 UTC
Read the original article Hit count: 176

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about spring

Related posts about spring-mvc