title: spring 4 enums as controller parameters
body: <p><strong>Later Edit</strong></p>
  
  <p>The case I described works properly. The problem appears when I have something like this on my controller's method:</p>
  
  <pre><code>@RestController 
  public class MyController {
    @RequestMapping(...)
    public void myMethod(@RequestBody MyForm myform) { ... }
  }
  
  public class MyForm {
    private X x;
    //setters and getters
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Cause</strong></p>
  
  <blockquote>
    <p>Given RequestBody, Spring will use an HttpMessageConverter to deserialize your request body into an instance of your given type. In this case, it will use MappingJackson2HttpMessageConverter for the JSON. This converter does not involve your PropertyEditorSupport at all.</p>
  </blockquote>
  
  <p>Any alternatives? I need to use <code>@RequestBody</code> in this case or find a way to put <code>X</code> into <code>myform</code>.</p>
  
  <hr>
  
  <p>I want to put an enum as a parameters inside a REST controller's method.</p>
  
  <p>This is what I've got so far.</p>
  
  <p>The enum:</p>
  
  <pre><code>public enum X {
    A("A"),B("B"),C("C");
    ... methods and constructors ...
  }
  </code></pre>
  
  <p>The controller:</p>
  
  <pre><code>@RestController 
  public class MyController {
    @RequestMapping(...)
    public void myMethod(@PathVariable("x") X x) { ... }
  }
  </code></pre>
  
  <p>The configuration:</p>
  
  <pre><code>@ControllerAdvice
  public class GlobalControllerConfig {
      @InitBinder
      public void registerCustomEditors(WebDataBinder binder, WebRequest request) {
        binder.registerCustomEditor(X.class, new XPropertyEditor());
      }
  }
  </code></pre>
  
  <p>The property editor:</p>
  
  <pre><code>public class XPropertyEditor extends PropertyEditorSupport {
      @Override
      public void setAsText(String text) {
          try {
              setValue(X.findByName(text));
          } catch (IllegalArgumentException e) {
              throw new IllegalArgumentException("Custom binding failed. Input type: String. Expected type of value to be set: X", e);
          }
      }
  
      @Override
      public String getAsText() {
          return ((X)getValue()).getName();
      }
  }
  </code></pre>
  
  <p>I put a breakpoint in my <code>@ControllerAdvice</code> and it passes through that binding each time a request is made to any of my controllers. This makes me think that the binding is correct.</p>
  
  <p>When I send a request to my method I get this and I don't understand why:</p>
  
  <pre><code>org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not construct instance of ...X from String value 'A': value not one of declared Enum instance names: [A, B, C]
  </code></pre>
  
  <p>Any suggestions?</p>