'@NotNull annotation doesn't throw exception
I have a problem. I want to throw an exception when an attribute is null, but the @NotNull annotation doesn't seem to be working. I use Spring 2.6.4
My controller:
@RestController
public class GroupController {
@RequestMapping(value = "/journey", method = RequestMethod.POST)
public ResponseEntity<Group> create(@Valid @RequestBody GroupCreateCommand groupCreateCommand, BindingResult bindingResult) throws Exception {
Group group = groupService.create(groupCreateCommand);
journeyService.notifyNewGroup(group);
return new ResponseEntity<>(group, HttpStatus.OK);
}
}
My class:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotNull;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class GroupCreateCommand {
@JsonProperty("id")
@NotNull
private Long id;
@JsonProperty("people")
@NotNull
private Integer people;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getPeople() {
return people;
}
public void setPeople(Integer people) {
this.people = people;
}
}
Request:
curl --location --request POST 'http://localhost:8080/journey' \
--header 'Content-Type: application/json' \
--data-raw '{
"id": 3
}'
As you can see, the exception is not thrown, but the seats attribute is mapped as null.
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
Thanks!
Solution 1:[1]
Here you are expecting validation result in BindingResult parameter.This parameter helps you in case you want some special handling for validation failures. you can remove BindingResult parameter from controller method or you can add below code snippet in controller method to view validation error for request body
if(bindingResult.hasErrors()){
bindingResult.getFieldErrors().stream().forEach(error -> {
System.out.println(error.getField() + ":" + error.getDefaultMessage());
});
}
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 | Ronak R |

