2

I have a Quarkus project with Smallrye reactive messaging based on Kafka. Since I want to work with a "complex pojo" I need a custom de-/serializer.

I'd like to make those two classes CDI beans so I can inject and use my custom logger, which is a CDI bean. Is there a way to achieve this?


Right now my injected logger object is simply null:

import org.apache.kafka.common.serialization.Serializer;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

@ApplicationScoped
public class MySerializer implements Serializer<MyDto>
{
    @Inject MyLogger logger;

    @Override public byte[] serialize(String topicName, MyDto myDto)
    {
        // this causes a java.lang.NullPointerException
        logger.info("serializing");

        ...
    }
}
Flo Ryan
  • 327
  • 1
  • 17

1 Answers1

2

As far as I know, you can only register a class name with kafka, and it will create that class internally, ie. without using CDI.

Possible workaround: make the registered object a thin wrapper around the CDI-bean, and delegate the work to the bean:

public class MySerializer implements Serializer<MyDto> {
    private MySerializerCdi delegate;

    public MySerializer() {
        delegate = CDI.current().select(MySerializerCdi.class).get();
    }

    @Override public byte[] serialize(String topicName, MyDto myDto) {
        return delegate.serialize(topicName, myDto);
    }
    ...
}

... and rename your original CDI class accordingly.

mtj
  • 3,381
  • 19
  • 30
  • Thank you mtj, this obviously creates some overhead but it seems to do the trick when I annotate `MySerializerCdi` with `@Provider` and `@ApplicationScoped`. I don't want to give up on trying to find a leaner solution just yet but otherwise I'll accept this answer - thanks! – Flo Ryan Jun 26 '20 at 17:54