Lombok 的 lombok.copyableAnnotations 无法使用 Jackson 注释

Lombok's lombok.copyableAnnotations not working with Jackson annotations

我正在尝试使用 Lombok 的新 copyableAnnotations 功能,以便将 @JsonIgnore@JsonValue 等 Jackson 注释复制到生成的 getter/wither 方法中。该博客似乎表明这应该有效:https://www.thecuriousdev.org/lombok-builder-with-jackson/。但是,当我尝试这个时,我只是得到 "error: annotation type not applicable to this kind of declaration" (指向我的 value 字段)。为什么这不起作用,我该如何使它起作用?也许我误解了这个功能应该如何工作。我正在使用 lombok 1.18.8.

model.java:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.Value;

import javax.validation.constraints.NotNull;

@Value
public class BrandId implements ValueObject<Long> {

    @JsonCreator
    public static BrandId of(final Long value) {

        return new BrandId(value);
    }

    @NotNull
    @JsonValue
    private Long value;
}

lombok.config:

config.stopBubbling = true

lombok.copyableAnnotations += com.fasterxml.jackson.annotation.JsonIgnore
lombok.copyableAnnotations += com.fasterxml.jackson.annotation.JsonProperty
lombok.copyableAnnotations += com.fasterxml.jackson.annotation.JsonValue

Why is this not working […] ?

@JsonValue 注解只允许在方法声明和其他注解类型的声明上使用;所以,不管有没有 Lombok,你都不能把它放在一个字段上。 (如果你查看 its Javadoc,你会看到它被注释为 @Target(value={ANNOTATION_TYPE,METHOD})。)

好消息是 @JsonValue 仅适用于 getter 方法(不适用于 setter 方法、生成器方法等),并且每个 class,所以手动创建那个没什么大不了的 getter:

    @NotNull
    private Long value;

    @JsonValue
    public Long getValue() {
        return value;
    }

如果您真的不喜欢它,那么您可以使用 Lombok 的实验性 onMethod 功能:

    @NotNull
    @Getter(onMethod=@__({@JsonValue}))
    private Long value;

除了是实验性的(所以它可能会在 Lombok 的未来版本中改变或消失 and/or Java)。