如何覆盖子项目中的自定义 Jackson 解串器?

How to override custom Jackson deserializer in child project?

在我们公司的图书馆里(比如说lib-a)我们有一个接口:

public interface MyInterface {
    ...
}

及其默认实现:

public enum DefaultMyImpl implements MyInterface {
    ...
}

它的序列化器:

public class DefaultMyInterfaceSerializer extends JsonDeserializer<MyInterface> {
    @Override
    public MyInterface deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        return parser.readValuesAs(DefaultMyImpl.class).next();
    }
}

对于杰克逊,我们有:

@Bean
public Jackson2ObjectMapperBuilderCustomizer defaultObjectMapperBuilderCustomizer() {
    return builder -> builder
            .deserializerByType(MyInterface.class, new DefaultMyInterfaceSerializer());
}

并且在依赖于 lib-a 的子项目中,我们可能有另一个实现:

public enum ChildMyImpl implements MyInterface {
    ...
}

及其序列化程序:

public class ChildMyInterfaceSerializer extends JsonDeserializer<MyInterface> {
    @Override
    public MyInterface deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        return parser.readValuesAs(ChildMyImpl.class).next();
    }
}

和它相关的 Jackson 配置:

@Bean
public Jackson2ObjectMapperBuilderCustomizer childObjectMapperBuilderCustomizer() {
    return builder -> builder
            .deserializerByType(MyInterface.class, new ChildMyInterfaceDeserializer());
}

但是,我似乎无法覆盖 MyInterfaceJackson2ObjectMapperBuilder 反序列化器。我在反序列化时收到此 Http 400 错误:

Bad Request: JSON parse error: Cannot deserialize value of type `com.company.library.domain.DefaultMyImpl` from String "SOME_STRING": not one of the values accepted for Enum class: [DEFAUL_ENUM_VAL]
 at [Source: (PushbackInputStream); line: 1, column: 30]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize value of type `com.company.library.domain.DefaultMyImpl` from String "SOME_STRING": not one of the values accepted for Enum class: [DEFAUL_ENUM_VAL]
 at [Source: (PushbackInputStream); line: 1, column: 30] (through reference chain: com.company.library.domain.MyInterface["..."])

认为是因为库中的自定义程序覆盖了我尝试放置的子项目:

@DependsOn(value = "defaultObjectMapperBuilderCustomizer")

@Order(value = Ordered.HIGHEST_PRECEDENCE)

在子定制器之上 @Bean 无济于事。如何以子项目覆盖依赖项 (lib-a) 的方式对它们进行排序?

我必须实施 BeanPostProcessor 并在那里覆盖它:

@Configuration
public class FinalJacksonConfiguration implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Jackson2ObjectMapperBuilder) {
            final Jackson2ObjectMapperBuilder builder = (Jackson2ObjectMapperBuilder) bean;
            builder.serializerByType(MyInterface.class, new ChildMyInterfaceDeserializer());
        }
        return bean;
    }
}