How to inject dependency into Jackson Custom deserializer

后端 未结 3 526
北恋
北恋 2020-12-19 04:32

I want to enable a custom jackson deserializer of some fields of type String. The deserializer also needs to be injected with a guice based dependency bean. SampleCode below

3条回答
  •  天涯浪人
    2020-12-19 05:04

    I haven't used Guice that much, but I guess it is somewhat similar to Spring. So I will post this answer here in case you can use the same principles as I have, and that someone using Spring reads this.

    First I annotate my Jackson module as a Spring @Component:

    @Component
    public class FlowModule extends SimpleModule {
    
    @Autowired private SupplierItemDeserializer supplierItemDeserializer;
    

    This means I can get whatever I want @Autowired into my module. As you can see I have also done the same thing to my de- / serializers:

    @Component
    public class SupplierItemDeserializer extends JsonDeserializer {
    
    @Autowired
    private SupplierService supplierService;
    

    I have then created a service that deals with converting to and from JSON:

    @Service
    public class IOService {
    
    private ObjectMapper mapper;
    
    @Autowired
    private FlowModule flowModule;
    
    
    @PostConstruct
    public void initialize() {
        mapper = new ObjectMapper();
        mapper.registerModule(flowModule);
        mapper.registerModule(new JavaTimeModule());
    }
    

    The service contains an ObjectMapper with my module that has all the right wiring.

提交回复
热议问题