【问题标题】:Can a custom serializer/deserializer be a Spring bean?自定义序列化器/反序列化器可以是 Spring bean 吗?
【发布时间】:2022-07-01 22:02:27
【问题描述】:

我在 POJO 中有一个字段,需要在序列化之前对其进行加密,并且类似地,在反序列化时解密。 问题是加密器是一个 Spring bean,所以我需要在我的自定义序列化器/反序列化器中访问 Spring 上下文。

我现在就是这样做的:

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

我想知道是否可以在不手动访问上下文的情况下自动连接cryptor。 将序列化器/反序列化器转换为 Spring bean 并没有帮助,因为 Jackson 使用无参数构造函数创建序列化器/反序列化器的实例,因此自动装配字段 cryptor 仍然是 null

一些代码来说明我在说什么:

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;
   }
}

提前致谢。

【问题讨论】:

    标签: java json spring jackson


    【解决方案1】:

    是的,可以。只需使用 @JsonComponent 注释。 我可以推荐你看看关于这个主题的 baeldung 文章:https://www.baeldung.com/spring-boot-jsoncomponent

    更新: 这里@JsonComponent 注释的javadoc:https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/jackson/JsonComponent.html

    【讨论】:

    • 请同时分享任何官方文档
    猜你喜欢
    • 2022-07-21
    • 2018-02-19
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 2021-02-06
    相关资源
    最近更新 更多