title: ConversionService in Spring
body: <p>I'm following this scheme in a Spring application.</p>
  
  <ol>
  <li>Request is sent to the server with the id of the object and some other params to be populated in this object </li>
  <li>The object with this id is loaded from the database</li>
  <li>getters and setters are invoked in this object to populate the values</li>
  <li>the object is then stored</li>
  </ol>
  
  <p>I asked in <a href="https://stackoverflow.com/questions/4335432/modelattribute-in-a-method">this other question</a> what was the best way to prepare the object before populate the params of the request. The answer was that the best way was to use a <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/validation.html#core-convert" rel="nofollow noreferrer">conversion service</a> instead of doing it in a @ModelAtribute annotated method or with an editor in the initBinder. </p>
  
  <p>So I have tried to use a converter, but I haven't found a similar example and I'm a little stuck. I have written a code like the one below: In the init binder I register the conversion service.  So before populating the values on the User object convert() method is invoked to load the object from the database. The problem is that this configuration doen't work because it is converting the id (username field) of the Object User into an Object user, but then it tries to make a setUsername() with the object so I get a "java.lang.IllegalArgumentException: argument type mismatch".</p>
  
  <p>Can anyone give me a clue  or an example of the way of using the ConversionService to get the desired behaviour?</p>
  
  <p>Thanks.</p>
  
  <pre><code>@Autowired
  private ConversionService conversionService;
  
  @InitBinder("user")
  public void initBinder(@RequestParam("username")String username, WebDataBinder binder){
      binder.setConversionService(conversionService);
  }
  
  @RequestMapping(value="/user/save", method=RequestMethod.POST)
  public String save(@ModelAttribute("user") User user, Model model) {        
      ...
  }
  </code></pre>
  
  <p>with something like:</p>
  
  <pre><code>@Component
  public class UserConversionService implements ConversionService{
      ...        
      @Override
      public Object convert(Object name, TypeDescriptor arg1, TypeDescriptor arg2) {
          return userService.find((String)name); 
      }
  }
  </code></pre>