【问题标题】:Combine multiple arbitrary annotations in one将多个任意注释合二为一
【发布时间】:2016-05-15 09:52:36
【问题描述】:

在我的代码中,我将有很多这样的 getter,它们具有相同的注释集(一个用于 Hibernate,其他用于 Jackson):

@Transient
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = BaseEntity.JSON_DATETIME_FORMAT)
public LocalDateTime getCreatedDateDT() {
    return DateTimeUtils.klabTimestampToLocalDateTime(getCreatedDate(), createdDateDT);
}

我想通过实现我自己的注释来最小化重复,这意味着所有这四个在一起,像这样:

@TransientLocalDateTime
public LocalDateTime getCreatedDateDT() {
    return DateTimeUtils.klabTimestampToLocalDateTime(getCreatedDate(), createdDateDT);
}

我该怎么做?这甚至可能吗?

更新 感谢 Konstantin Yovkov,现在我知道了,我可以将所有 Jackson 注释合二为一,但那是因为 Jackson 的注释处理器识别出这样的技巧。我想知道是否可以让 any 注释处理器做到这一点?在我看来不是。

【问题讨论】:

    标签: java hibernate annotations jackson


    【解决方案1】:

    Jackson 提供了一个元注解(注解用于注解另一个注解),称为@JacksonAnnotationsInside,它是一个:

    元注释(用于其他注释的注释)用于 表示不使用目标注解(注解 使用此注释进行注释),杰克逊应该使用元注释 它有。

    这对于创建“组合注释”很有用 容器注解,需要用这个注解注解 以及它“包含”的所有注释。

    所以,你应该像这样创建一个注解:

    @Target(value = { ElementType.TYPE, ElementType.METHOD,
                      ElementType.PARAMETER, ElementType.FIELD })
    @Retention(RetentionPolicy.RUNTIME)
    @JacksonAnnotationsInside // <-- this one is mandatory
    @Transient
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = BaseEntity.JSON_DATETIME_FORMAT)
    public @interface TransientLocalDateTime {    
    }
    

    使用方式如下:

    @TransientLocalDateTime
    public LocalDateTime getCreatedDateDT() {
        return DateTimeUtils.klabTimestampToLocalDateTime(getCreatedDate(), createdDateDT);
    }
    

    【讨论】:

    • 这很有帮助,但它可以用于任意注释还是仅用于杰克逊的注释?这里似乎不允许使用@Transient
    • I可以用于任意注释,但只能由Jackson注释处理器处理......除非你编写自定义注释处理器,但我相信你可以引入一个全新的注释(而不要使用@JacksonAnnotationsInside ),它由您的注释处理器处理。
    • 另外,我的 IDE 中出现 @TransientLocalDateTime not applicable to method 错误。
    • 对于后一个错误,只需将其设置为@Target(value = { ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD }) 即可在每个可能的元素上使用它。
    猜你喜欢
    • 2016-02-02
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2019-11-06
    • 2016-03-18
    • 2010-12-15
    相关资源
    最近更新 更多