簡體   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