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"]
}
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.
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.
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.
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).
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With