Spring Boot Immutable validation only work with get prefix

498 Views Asked by At

I am trying to implement Javax Validation on Immutable objects, but I only get it working by renaming every variable with prefix "get". It is possible to make it work without that "get" ?

    @Value.Immutable
    public interface Entity {
        @Min(19)
        int getAge();

        @NotBlank
        @Size(min = 10)
        String getName();

    }

my controller:

@PostMapping("/entity/")
public ResponseEntity post2(@RequestBody @Valid ImmutableEntity entity) {


    return  new ResponseEntity<Object>("", HttpStatus.OK);
}
1

There are 1 best solutions below

6
João Dias On

If I understand @Value.Immutable correctly, you are supposed to annotate it on a class or interface with the methods representing the to-be-generated fields. Example:

@Value.Immutable
public interface Entity {
    int getAge();
    String getName();
}

This would mean that the following would be generated:

@Generated(from = "Entity", generator = "Immutables")
public final class ImmutableEntity implements Entity {
  private final int age;
  private final String name;

  private ImmutableEntity(int age, String name) {
    this.age = age;
    this.name = name;
  }

  @Override
  public int getAge() {
    return age;
  }

  @Override
  public String getName() {
    return name;
  }

  (...)
}

If you do not follow the getXXXXX() pattern you will get a different generated class as follows:

@Value.Immutable
public interface Entity {
    int age();
    String name();
}

With this one you would get the following generated class:

@Generated(from = "Entity", generator = "Immutables")
public final class ImmutableEntity implements Entity {
  private final int age;
  private final String name;

  private ImmutableEntity(int age, String name) {
    this.age = age;
    this.name = name;
  }

  @Override
  public int age() {
    return age;
  }

  @Override
  public String name() {
    return name;
  }

  (...)
}

Mind the differences. In the first one, you have normal getters, in the second one you have "getters" without the prefix get in the method name. Javax Validation uses normal getters to get the data so that it can be validated. In the second generated class, you getters do not follow the usual naming convention, and thus Javax Validation does not work.