6

Welcome,

I've created simple Rest Controller:

 @RestController
 public class MyController {
    @PostMapping(value = "/cities", consumes = "application/json", produces = "application/json")
    public String getCities(@RequestBody Request request) {
        return request.getId();
    }
}

I want Request class to be immutable.

Is it ok to use Immutable with Lombok this way ?

import com.google.common.collect.ImmutableList;
import java.beans.ConstructorProperties;
import java.util.List;
import jdk.nashorn.internal.ir.annotations.Immutable;
import lombok.Getter;
import lombok.Value;

@Immutable
@Value
public final class Request {

    private final String id;
    private final ImmutableList<String> lista;

    @ConstructorProperties({"id", "lista"})
    public Request(String id, List<String> lista) {
        this.id = id;
        this.lista = ImmutableList.copyOf(lista);
    }

}

Request JSON:

{
"id":"g",
"lista": ["xxx","yyy"]
}
piotrassss
  • 205
  • 1
  • 4
  • 10

2 Answers2

7

You can add lombok.config file to your project with enabled addConstructorProperties property:

lombok.anyConstructor.addConstructorProperties=true

then Lombok will generate a @java.beans.ConstructorProperties annotation when generating constructors.

So you will not need to specify a constructor explicitly:

@Value
public class Request {
    private String id;
    private ImmutableList<String> list;
}

And Jackson will be able to deserialize your object.


More info:

Cepr0
  • 28,144
  • 8
  • 75
  • 101
1

Value is immutable itself, no need for @Immutable. To make it Jackson-serializable use Lombok's private @NoArgsConstructor:

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.Value;

@Value
@NoArgsConstructor(force = true, access = AccessLevel.PRIVATE)
public class Request {

  Integer id;
  String name;
}
Zon
  • 18,610
  • 7
  • 91
  • 99