spring web starter 中路径变量的自定义反序列化

Custom deserialization of path variable in spring web starter

在 Spring web reactive 中为路径变量注册自定义解串器的正确方法是什么?

示例:

@GetMapping("test/{customType}")
public String test(@PathVariable CustomType customType) { ...

我尝试了 ObjectMapperBuilder、ObjectMapper 并直接通过 @JsonDeserialize(using = CustomTypeMapper.class) 但它不会注册:

Response status 500 with reason "Conversion not supported."; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type '...CustomType'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type '...CustomType': no matching editors or conversion strategy found

我最终使用了@ModelValue,因为它在语义上不是反序列化,只是解析一个键。

@RestController
public class FooController {

   @GetMapping("test/{customType}")
   public String test(@ModelAttribute CustomType customType) { ... }
}

@ControllerAdvice
public class GlobalControllerAdvice {

   @ModelAttribute("customType")
   public CustomType getCustomType(@PathVariable String customType) {
      CustomeType result = // map value to object
      return result;
   }
}

路径变量反序列化不需要jackson,可以使用org.springframework.core.convert.converter.Converter

例如:

@Component
public class StringToLocalDateTimeConverter
  implements Converter<String, LocalDateTime> {

    @Override
    public LocalDateTime convert(String source) {
        return LocalDateTime.parse(
          source, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    }
}

@GetMapping("/findbydate/{date}")
public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) {
    return ...;
}

Here's an article 示例