将jsoncomponent与rabbitlistener结合使用

tct7dpnv  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(332)

我正在尝试使用自定义反序列化程序:

@JsonComponent
class SuffixDeserializer extends JsonDeserializer<String> {

    private final String suffix;

    SuffixDeserializer(@Value("${suffix}") String suffix) {
        this.suffix = suffix;
    }

    @Override
    public String deserialize(JsonParser json, DeserializationContext ctx) 
            throws IOException {
        return json.getText() + suffix;
    }
}

对于rabbitmq侦听器:

@Slf4j
@Service
class FooListener {

    @RabbitListener(queuesToDeclare = @Queue(name = "foo", durable = "true"))
    void foo(Message msg) {
        log.info("Received {}", msg);
    }

    @Data
    static class Message {
        @JsonDeserialize(using = SuffixDeserializer.class)
        private String field;
    }
}

我甚至试着注册 JsonComponentModule 明确地:

@Bean
public MessageConverter jsonConverter() {
    ObjectMapper mapper = new ObjectMapper()
            .registerModule(new JsonComponentModule());
    return new Jackson2JsonMessageConverter(mapper);
}

但当我运行此代码时,会出现以下错误:

Caused by: com.fasterxml.jackson.databind.JsonMappingException: Class io.github.jjarzynski.jsoncomponentmq.SuffixDeserializer has no default (no arg) constructor
 at [Source: (String)"{"field": "bar"}"; line: 1, column: 1]

这意味着jackson正在尝试创建自己的示例,而不是使用springbean。
如何将自定义springbean反序列化器应用于传入rabbitmq消息中的字段?

qf9go6mv

qf9go6mv1#

例外情况清楚地表明:
suffixdeserializer在[source:(string)“{”field“:”bar“}”处没有默认(无参数)构造函数;行:1,列:1]
因此,您需要在suffixdeserializer类上放置一个默认构造函数,可能还需要getter和setter来设置后缀。

@JsonComponent
class SuffixDeserializer extends JsonDeserializer<String> {

    private String suffix;

    SuffixDeserializer() {}

    SuffixDeserializer(@Value("suffix") String suffix) {
        this.suffix = suffix;
    }

    @Override
    public String deserialize(JsonParser json, DeserializationContext ctx) 
            throws IOException {
        return json.getText() + suffix;
    }
}
0g0grzrc

0g0grzrc2#

我唯一能使用 SuffixDeserializer bean是通过以下方式注册的:

@Bean
MessageConverter jsonConverter(SuffixDeserializer deserializer) {

    SimpleModule jsonComponentModule = new JsonComponentModule()
            .addDeserializer(String.class, deserializer);

    ObjectMapper mapper = new ObjectMapper()
            .registerModule(jsonComponentModule);

    return new Jackson2JsonMessageConverter(mapper);
}

这表明 @JsonComponent 扫描对rabbitmq没有用?我不妨做个注解 SuffixDeserializer@Component .

相关问题