制作了一个单独的注解

制作了一个单独的注解

本文介绍了Java 制作了一个单独的注解,结合了其他注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Play Framework 2.2,制作 RESTfull API.

Working with Play Framework 2.2, making a RESTfull API.

在我使用的模型中,我只想输出(Json with Jackson)相关对象的 Id,而不是整个对象.我找到了如何做到这一点,如下所示:

In a model I'm using, I wanted to output(Json with Jackson) only the Id of a related object, not the entire object. I found how to do that, as follows:

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
@JsonIgnore
public Object myObject;

Json 输出将包含一个 JsonNode "myObjectId: 1".例如.

The Json output will contain a JsonNode "myObjectId: 1". For instance.

IdentityInfo 和 IdentityReference 负责处理这一点.

The IdentityInfo and IdentityReference take care of this.

问题是,无论我想要什么,我都必须粘贴这 3 行,以及某个字段需要存在的任何其他注释.这变得太大了,我正在尝试只创建 1 个自定义注释来同时完成所有这些事情.

The problem is, wherever I want this, I have to paste down these 3 lines, along with any other annotations that need to be present for a certain field. This get grow too large and I'm trying to create just 1 custom annotation that does all these things together.

这可能吗,怎么做?一个我可以阅读它的链接或一个例子将不胜感激.

Is this possible, and how? A link where I can read about it or an example would be appreciated.

推荐答案

要解决您的问题,您必须创建一个注释为 JacksonAnnotationInside 以及您希望它包含"的注释.

To solve your problem you have to create an annotation annotated with JacksonAnnotationInside and annotations you want it to 'include'.

那个注解的 Javadoc 说它是:

The Javadoc of that annotation says that it is:

元注释(用于其他注释的注释)用于表示不是使用目标注解(annotation使用此注释进行注释),Jackson 应该使用元注释它有.这在创建组合注释"时很有用容器注解,需要用这个注解以及它包含"的所有注释.

例如对于你的情况,你会有这样的事情:

For example for your case you'd have something like this:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@com.fasterxml.jackson.annotation.JacksonAnnotationsInside // this is important
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
public @interface MyCustomAnnotation {
}

然后你可以像使用Jackson注解一样正常使用它

Then you can use it normally as you would Jackson annotations

@MyCustomAnnotation
public Object myObject;

这篇关于Java 制作了一个单独的注解,结合了其他注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 01:57