逐场指定转换器

时间:2019-08-02 14:46:30

标签: java spring-data spring-data-mongodb

我希望能够逐个字段指定Converter的类型。为此,我创建了一个注释,以指定要使用的所需转换器类。我还创建了一个实现GenericConverter和ConditionalConverter的类。我从getConvertibleTypes返回null表示我要检查所有源对。在matches方法内部,我将检查是否存在我的自定义注释,然后使用指定的转换器类。我的问题是,当我调用save时,仅以matches作为sourceType和Long作为targetType来调用ObjectId方法。我是用正确的方法吗?

public class ConvertWithConditionalConverter implements GenericConverter, ConditionalConverter {

  @Override
  public boolean matches(TypeDescriptor sourceTypeDesc, TypeDescriptor targetTypeDesc) {
      // Only ever gets called with Long and ObjectId
      System.out.println("Source: " + sourceTypeDesc.getName() + ", Target: " + targetTypeDesc.getName());
      return false;
  }

  @Override
  public @Nullable Set<ConvertiblePair> getConvertibleTypes() {
      // Returning null indicates all source-to-target pairs should be considered.
      return null;
  }

  @Override
  public Object convert(@Nullable Object source, TypeDescriptor sourceTypeDesc, TypeDescriptor targetTypeDesc) {
      // Never gets called
      System.out.println("Source: " + sourceTypeDesc.getName() + ", Target: " + targetTypeDesc.getName());
      return null;
  }
}

我要使用字段注释的注释

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ConvertWith {
  Class<? extends Converter> value();
}

0 个答案:

没有答案