Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Lombok in immutable Request class

Tags:

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"]
}
like image 223
piotrassss Avatar asked May 06 '19 19:05

piotrassss


People also ask

Is Lombok builder immutable?

The example does not demonstrate other useful Lombok features like @Builder or @With which will help you create builder and copy methods. Be aware that Lombok is not an immutability library but a code generation library which means some setups might not create immutable objects.

What is @value annotation in Lombok?

The @Value annotation is one of the annotations from Project Lombok that is added to Java classes to make them and their instances immutable. Immutable is just fancy word for non-changeable. This means that immutable objects cannot have their fields changed once they are initialized.

What is Lombok jar used for?

Project Lombok (from now on, Lombok) is an annotation-based Java library that allows you to reduce boilerplate code. Lombok offers various annotations aimed at replacing Java code that is well known for being boilerplate, repetitive, or tedious to write.

Does spring boot use Lombok?

Lombok Dependency Note: If you're using a Spring Boot POM, Project Lombok is a curated dependency. Thus, you can omit the version (which will then be inherited from the Spring Boot parent POM).


1 Answers

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:

  • Lombok config
  • Lombok @Value
like image 170
Cepr0 Avatar answered Oct 05 '22 00:10

Cepr0