Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I register a custom type converter in Spring?

Tags:

java

spring

I need to pass a UUID instance via http request parameter. Spring needs a custom type converter (from String) to be registered. How do I register one?

like image 342
alexei.vidmich Avatar asked Sep 15 '08 23:09

alexei.vidmich


3 Answers

Please see chapter 5 of the spring reference manual here: 5.4.2.1. Registering additional custom PropertyEditors

like image 145
MetroidFan2002 Avatar answered Oct 19 '22 22:10

MetroidFan2002


I have an MVC controller with RequestMapping annotations. One method has a parameter of type UUID. Thanks toolkit, after reading about WebDataBinder, I figured that I need a method like this in my controller:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(UUID.class, new UUIDEditor());
}

UUIDEditor simply extends PropertyEditorSupport and overrides getAsText() and setAsText().

Worked for me nicely.

like image 22
alexei.vidmich Avatar answered Oct 20 '22 00:10

alexei.vidmich


In extenstion to the previous example.

Controller class

@Controller
@RequestMapping("/showuuid.html")
public class ShowUUIDController
{

  @InitBinder
  public void initBinder(WebDataBinder binder)
  {
    binder.registerCustomEditor(UUID.class, new UUIDEditor());
  }

  public String showuuidHandler (@RequestParam("id") UUID id, Model model)
  {
    model.addAttribute ("id", id) ;
    return "showuuid" ;
  }
}

Property de-munger

class UUIDEditor extends java.beans.PropertyEditorSupport
{

  @Override
  public String getAsText ()
  {
    UUID u = (UUID) getValue () ;
    return u.toString () ;
  }

  @Override
  public void setAsText (String s)
  {
    setValue (UUID.fromString (s)) ;
  }

}
like image 36
David Newcomb Avatar answered Oct 19 '22 22:10

David Newcomb