有没有办法从元注释中注入Jackson注释值,类似于Spring的AliasFor注释?

dev*_*eed 7 java spring annotations jackson

我们正在使用@JacksonAnnotationsInside并希望使用元注释从类中注入属性.

即我们有一个元注释,@JsonTypeInfo()并希望通过聚合注释注入defaultImpl.

这是我正在尝试使用的注释:

@Inherited
@JacksonAnnotationsInside
@Retention(RetentionPolicy.RUNTIME)
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class") //, defaultImpl=defaultType())
public @interface PolymorphismSupport {
    //@AliasFor("defaultImpl") ...
    Class<?> defaultType() default Object.class;
}
Run Code Online (Sandbox Code Playgroud)

Rag*_*ghu 3

Jackson 中不提供类似AliasFor的支持。但是作为一种解决方法,我们可以通过扩展来修改注释提供的元数据的消耗JacksonAnnotationIntrospector

您想要实现的目标可以通过提供自定义来完成,JacksonAnnotationIntrospector该自定义将提供注释中的默认实现PolymorphismSupport

@Inherited
@JacksonAnnotationsInside
@Retention(RetentionPolicy.RUNTIME)
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
public @interface PolymorphismSupport {

    Class<?> defaultType() default Object.class;

}

public class CustomAnnotationIntrospector extends JacksonAnnotationIntrospector {

    @Override
    protected TypeResolverBuilder<?> _findTypeResolver(MapperConfig<?> config, Annotated ann, JavaType baseType) {
        TypeResolverBuilder<?> b = super._findTypeResolver(config, ann, baseType);
        PolymorphismSupport support = _findAnnotation(ann, PolymorphismSupport.class);
        if (null != b && null != support) {
            b.defaultImpl(support.defaultType());
        }
        return b;
    }
}


public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        setAnnotationIntrospector(new CustomAnnotationIntrospector());
    }
}
Run Code Online (Sandbox Code Playgroud)

这种方法的唯一缺点是您必须在初始化时将内省器注册到对象映射器中。