繁体   English   中英

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

[英]Is there a way to inject Jackson annotation values from a meta annotation, similar to Spring's AliasFor annotation?

我们正在使用@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;
}

在Jackson中没有AliasFor like支持。但作为一种解决方法,我们可以通过扩展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());
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM