Spring 引导 MVC/Rest 控制器和枚举反序列化转换器

Spring Boot MVC/Rest controller and enum deserialization converter

在我的 Spring 引导应用程序中,我有以下 @RestController 方法:

@RequestMapping(value = "/{decisionId}/decisions", method = RequestMethod.POST)
    public List<DecisionResponse> getChildDecisions(@PathVariable Long decisionId, @Valid @RequestBody Direction direction) {
    }

我使用枚举 org.springframework.data.domain.Sort.Direction 作为请求主体。

现在 Spring 内部逻辑无法在客户端请求后反序列化此 Direction 枚举。

您能否展示如何编写自定义枚举转换器(或类似的东西)并使用 Spring Boot 配置它以便能够反序列化来自客户端请求的 Direction 枚举?也应该允许 null 值。

首先你应该创建自定义转换器 class,实现 HttpMessageConverter<T> 接口:

package com.somepackage;

public class DirectionConverter implements HttpMessageConverter<Sort.Direction> {

    public boolean canRead(Class<?> aClass, MediaType mediaType) {
        return aClass== Sort.Direction.class;
    }

    public boolean canWrite(Class<?> aClass, MediaType mediaType) {
        return false;
    }

    public List<MediaType> getSupportedMediaTypes() {
        return new LinkedList<MediaType>();
    }

    public Sort.Direction read(Class<? extends Sort.Direction> aClass,
                                 HttpInputMessage httpInputMessage) 
                                 throws IOException, HttpMessageNotReadableException {   

        String string = IOUtils.toString(httpInputMessage.getBody(), "UTF-8");
        //here do any convertions and return result 
    }

    public void write(Sort.Direction value, MediaType mediaType, 
                      HttpOutputMessage httpOutputMessage) 
                      throws IOException, HttpMessageNotWritableException {

    }

}

我使用 Apache Commons IO 中的 IOUtilsInputStream 转换为 String。但您可以选择任何首选方式。

现在您已在 Spring 个转换器列表中注册创建的转换器。接下来添加到 <mvc:annotation-driven> 标签中:

 <mvc:annotation-driven>
     <mvc:message-converters>
         <bean class="com.somepackage.DirectionConverter"/>
     </mvc:message-converters>
 </mvc:annotation-driven>

或者如果您使用的是 java 配置:

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(
      List<HttpMessageConverter<?>> converters) {    
        messageConverters.add(new DirectionConverter()); 
        super.configureMessageConverters(converters);
    }
}