'Can a custom serializer/deserializer be a Spring bean?

I have a field in a POJO which needs to be encrypted before being serialized and, similarly, decrypted upon deserialization. The issue is that a cryptor is a Spring bean, so I need to access Spring context in my custom serializers/deserializers.

That's how I do that now:

private static final Cryptor cryptor = ApplicationContextUtils.getApplicationContext().getBean(Cryptor.class);

I wonder though if it's possible to autowire cryptor without accessing the context manually. Converting the serializer/deserializer to Spring beans doesn't help, as Jackson creates an instance of a serializer/deserializer using a no-args constructor, so an autowired field cryptor remains null.

A bit of code to illustrate what I'm talking about:

public class POJO {
 
  @JsonSerialize(using = EncryptSerializer.class)
  @JsonDeserialize(using = DecryptDeserializer.class)
  private String code;
}
public class EncryptSerializer extends JsonSerializer<String> {

  private static final Cryptor cryptor = ApplicationContextUtils.getApplicationContext().getBean(Cryptor.class);
  
  @Override
  public void serialize(String value, JsonGenerator generator, SerializerProvider serializers) throws IOException {
        if (value != null) {
            generator.writeString(cryptor.encrypt(value));
        }
   }
}
public class DecryptDeserializer extends JsonDeserializer<String> {
 
   private static final Cryptor cryptor = ApplicationContextUtils.getApplicationContext().getBean(Cryptor.class);

   @Override
   public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String value = jsonParser.getValueAsString();
        return (value != null) ? cryptor.decrypt(value) : null;
   }
}

Thanks in advance.



Solution 1:[1]

Yes, it can. Just use @JsonComponent annotation. I can recommend u to see baeldung article about this theme: https://www.baeldung.com/spring-boot-jsoncomponent

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ?????? ?????????