带有Spring Boot Webflux的自定义转换器未调用

问题描述

在Java 14,版本2.3.3中使用spring-boot-starter-webflux,我试图注册一个自定义转换器,以将String输入转换为枚举。我遇到的问题是,在执行时,底层的Jackson库会尝试在不考虑我已注册自定义转换器的情况下转换String。

这是我使用的控制器:

@RestController
public class MyController {

    private final MyService myService;


    @Autowired
    public MyController(MyService myService) {
        this.myService = myService;
    }

    @PostMapping(value = "/subscriptions")
    public CreateSubscriptionOutput createSubscription(@RequestBody @Valid CreateSubscriptionInput input) throws Exception {
        return myService.createSubscription(input);
    }

}

输入定义如下:

public class CreateSubscriptionInput {

    private EventType eventType;

    public CreateSubscriptioninput() {
        this.eventType = EventType.A;
    }

    public CreateSubscriptionInput(EventType type) {
        this.eventType = type;
    }

    public EventType getEventType() {
        return this.eventType;
    }

}

public enum EventType implements SafeEnum {

    A(0L,"a"),B(1L,"b"),private final long id;
    private final String name;

    public static EventType from(long id) {
        return (EventType) Enums.from(EventType.class,id);
    }

    public static EventType from(String name) {
        return (EventType) Enums.from(EventType.class,name);
    }

    private EventType(long id,String name) {
        this.id = id;
        this.name = name;
    }

    public long getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

}

public interface SafeEnum {

    long getId();

    String getName();

}

public final class Enums {

    public static <E extends Enum<E> & SafeEnum> E from(Class<E> clazz,long id) {
        for (E e : EnumSet.allOf(clazz)) {
            if (e.getId() == id) {
                return e;
            }
        }

        throw new IllegalArgumentException("UnkNown " + clazz.getSimpleName() + " id: " + id);
    }

    public static <E extends Enum<E> & SafeEnum> E from(Class<E> clazz,String name) {
        if (name == null) {
            return null;
        }

        for (E e : EnumSet.allOf(clazz)) {
            if (e.getName().equals(name)) {
                return e;
            }
        }

        throw new IllegalArgumentException("UnkNown " + clazz.getSimpleName() + " name: " + name);
    }

}

自定义转换器的定义和注册如下:

@Configuration
@EnableWebFlux
public class ApplicationConfiguration implements WebFluxConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new Converter<String,EventType>() {
            @Override
            public EventType convert(String source) {
                return EventType.from(source);
            }
        });
    }

目的是将“ a”转换为EventType.A

当我按如下方式调用REST资源时:

curl --location --request POST 'http://localhost:8081/subscriptions' \
     --header 'Content-Type: application/json' \
     --data-raw '{
         "eventType": "a",}'

我收到400错误,并显示以下内部错误

JSON解码错误:无法反序列化类型的值 来自字符串“ a”的my.app.EventType:不是以下其中一种可接受的值 枚举类别:[A,B]

这让我认为转换器从未被调用。在调试中运行代码可以确认这一假设。在DEBUG中设置root记录程序似乎无法显示有关已注册转换器的信息。

我如何注册转换器有问题吗?缺少什么?

解决方法

不清楚在用@RequestBody注释的DTO中反序列化值时为什么不使用注册的转换器。官方文档似乎没有描述这种情况。希望一种解决方法是使用@JsonCreator批注:

public enum EventType implements SafeEnum {

    A(0L,"a"),B(1L,"b"),private final long id;
    private final String name;

    public static EventType from(long id) {
        return (EventType) Enums.from(EventType.class,id);
    }

    @JsonCreator
    public static EventType from(String name) {
        return (EventType) Enums.from(EventType.class,name);
    }

    private EventType(long id,String name) {
        this.id = id;
        this.name = name;
    }

    public long getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

}

这不太灵活,需要对所有枚举进行重复,但是至少它具有按预期工作的优点。

,

在没有 WebFluxConfigurer 的情况下使用 Converter 作为 @Component :

@Component
public class CustomConverter implements Converter<String,EventType> {
    @Override
    public EventType convert(String source) {
        return EventType.from(source);
    }
}