piotrassss
piotrassss

Reputation: 315

Using Lombok in immutable Request class

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"]
}

Upvotes: 6

Views: 3009

Answers (2)

Zon
Zon

Reputation: 19880

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;
}

Upvotes: 1

Cepr0
Cepr0

Reputation: 30309

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:

Upvotes: 7

Related Questions