FMC
FMC

Reputation: 660

Spring MVC force Jackson to only use setters

I have a Spring MVC application which uses Jackson and the @RequestBody annotation.

I have a field in the POJO that I do not want Jackson to map, so I have lombok set the setter access level to NONE.

@NotNull
@Setter(AccessLevel.NONE)
private boolean enabled = false;

I have tried to force Spring's ObjectMapper bean to only use setters by configuring as:

@Bean
@Primary
public ObjectMapper getObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.NONE);
    return mapper;
}

I would assume that with no setter and no visability of the field Jackson would not map up the "enabled" field... but if I send a body with enabled set to true it maps it,

Can anyone advise what else I need to do?

Thanks

Upvotes: 2

Views: 886

Answers (1)

Strelok
Strelok

Reputation: 51481

Just annotate the field with @JsonProperty and set access to read only.

@JsonProperty(access = Access.READ_ONLY)
private boolean enabled;

PS. You don't need to annotate with @NotNull or initialise to false since you're using a primitive type.

Upvotes: 3

Related Questions