简体   繁体   中英

How do I register a custom type converter in 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?

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

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.

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)) ;
  }

}

Not sure what you are asking?

Spring comes with a CustomEditorConfigurer to supply custom String <-> Object converters.

To use this, just add the CustomEditorConfigurer as bean to your config, and add the custom converters. However, these converters are typically used when converting string attributes in the config file into real objects.

If you are using Spring MVC, then take a look at the section on annotated MVC

Specifically, have a look at the @RequestParam and the @ModelAttribute annotations?

Hope this helps?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM