I'm trying to make use of Lombok's new copyableAnnotations
feature in order to have Jackson annotations like @JsonIgnore
and @JsonValue
copied to generated getter/wither methods. This blog seems to suggest this should work: https://www.thecuriousdev.org/lombok-builder-with-jackson/. However, when I try this I simply get "error: annotation type not applicable to this kind of declaration" (pointing to my value
field). Why is this not working and how do I make it work? Perhaps I'm misunderstanding how this feature is supposed to work. I'm using 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 […] ?
The @JsonValue
annotation is only allowed on method declarations and on declarations of other annotation types; so, with or without Lombok, you can't put it on a field. (If you look at its Javadoc, you'll see that it's annotated with @Target(value={ANNOTATION_TYPE,METHOD})
.)
The good news is that @JsonValue
only applies to getter methods (not setter methods, builder methods, etc.), and there can be only one of it per class, so it's not a big deal to just manually create that one getter:
@NotNull
private Long value;
@JsonValue
public Long getValue() {
return value;
}
If you really dislike that, then you can use Lombok's experimental onMethod
feature:
@NotNull
@Getter(onMethod=@__({@JsonValue}))
private Long value;
which is equivalent to the above except in being experimental (so it may change or disappear in future versions of Lombok and/or Java).