Java制作了一个单独的注释,它结合了其他注释 [英] Java make a separate annotation that combines a others

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

问题描述

使用Play Framework 2.2,制作RESTfull API。

Working with Play Framework 2.2, making a RESTfull API.

在我正在使用的模型中,我想输出(Json与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输出将包含一个JsonNodemyObjectId:1。例如。

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

IdentityInfo和IdentityReference会处理这个问题。

The IdentityInfo and IdentityReference take care of this.

问题是,无论我想要哪个地方,我必须粘贴这3行,以及需要为某个字段提供的任何其他注释。这变得越来越大,我正在尝试创建一个自定义注释来完成所有这些事情。

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:


用于
的元注释(用于其他注释的注释)表示不使用目标注释(注释
使用此注释注释),杰克逊应使用meta -annotations
它有。 这可以通过使用
容器注释来创建组合注释,这需要使用此注释
以及它包含的所有注释进行注释。

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

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 {    
}

然后你可以正常使用它,因为你可以使用杰克逊注释

Then you can use it normally as you would Jackson annotations

@MyCustomAnnotation
public Object myObject;

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆