在我的代码中,我将使用相同的一组注释(一个用于 Hibernate,另一个用于 Jackson)使用很多像这样的 getter:
@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 注释处理器做到这一点?在我看来,它不是。
最佳答案
Jackson 提供了一个元注解(用于注解另一个注解的注解),称为@JacksonAnnotationsInside
。 ,这是一个:
Meta-annotation (annotations used on other annotations) used for indicating that instead of using target annotation (annotation annotated with this annotation), Jackson should use meta-annotations it has.
This can be useful in creating "combo-annotations" by having a container annotation, which needs to be annotated with this annotation as well as all annotations it 'contains'.
因此,您应该创建这样的注释:
@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);
}
关于java - 将多个任意注释合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35223833/