如何创建一组杰克逊注释的注释?

2022-08-31 22:35:56

大约一年前,我读了一篇文章,解释了如何创建一个注释,它基本上是其他注释的容器。这样,如果我总是在特定用例中使用相同的5个注释,我会创建一个包含它们的注释并改用它。

不幸的是,我再也找不到这篇文章了,现在真的想为我的jackson配置做这件事。

由于我自己找不到任何有关这方面的信息,我开始质疑我的记忆力。这可能吗,或者我只是错了?

编辑

我想要的是这样的东西:

@Target(ElementType.METHOD)
@com.fasterxml.jackson.databind.annotation.JsonSerialize(using=MySerializerThatIsUsedEverywhere.class
@javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter(MyCustomXmlAdapter.class)
@SomeOtherEvaluatedByTheSerializer
public @interface SerializerUseCase01 {
    public String a();
    public int b();
)

我的场景是,我有一堆序列化用例,可以由具有不同配置的同一序列化程序处理。为了使所有内容更易于使用和透明,我想将jackson配置和序列化程序配置包装到一个注释中。


答案 1

对于 Jackson 来说,这可以通过元注释来完成。有关详细信息,请参阅此文章,但其中的代码片段是:@JacksonAnnotationsInside

@Retention(RetentionPolicy.RUNTIME) // IMPORTANT
@JacksonAnnotationsInside
@JsonInclude(Include.NON_NULL)
@JsonPropertyOrder({ "id", "name" }) 
public @interface MyStdAnnotations

从那时起,您可以将此类型用于自己的类,如下所示:

@MyStdAnnotations
public class MyBean {
   public String name, id;
}

答案 2

这里有一些关于如何制作包含其他批注的批注的各种组合的示例。这是你要找的吗?

来自源的示例:

@Target(ElementType.METHOD)
public @interface SimpleAnnotation {
    public String a();
    public int b();
)

@Target(ElementType.METHOD)
public @interface ReallyComplexAnnotation {
    public SimpleAnnotation[] value();
)

使用如下:

@ReallyComplexAnnotation(
    { @SimpleAnnotation(a="...", b=3), @SimpleAnnotation(a="...", b=4) }
)

推荐