'@Size annotation doesn't seem to work for my class

I have a Spring Boot Controller with an endpoint that accepts the following Configuration class (as json). The class has the param maxIterations and has a @Size annotation set to 9000.

...
import javax.validation.constraints.Max;
import javax.validation.constraints.Size;

public class Configuration {
    // Max iterations
    @Size(max = 9000)
    private Integer maxIterations;

    ...
}

The problem is that when making the POST call to that endpoint with the following json it does not return an error or warning stating the the maxIterations parameter is higher than 9000.

{
  "maxIterations": 15000
}

This is my controller:

@PostMapping()
@ResponseStatus(HttpStatus.CREATED)
public String doSomething(@RequestBody Configuration configuration) {
    ...
}

What can be the issue?



Solution 1:[1]

As mentioned in the comments, you should be using @Max(9000) as @Size should only be used for arrays, Strings, collections and maps.

public class Configuration {
    @Max(9000)
    private Integer maxIterations;

    // ...
}

Additionally, you should use the @Valid annotation within your controller so that the bean validator knows that there are constraints within the Configuration class, for example:

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public String doSomething(@Valid @RequestBody Configuration configuration) {
    // ...
}

This only works if you have a proper implementation of the Java Validation API on your classpath. This can be done by adding the following dependency:

<dependency>
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-validation</artifactId> 
</dependency>

Before Spring boot 2.3, this was automatically included within the spring-boot-starter-web dependency, but now you have to manually include the dependency.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1