I have a controller looks like this:
@RestController
@RequestMapping(value="/api/events")
public class EventController{
@Inject
private EventValidator eventValidator;
@InitBinder
@Qualifier("eventValidatior")
private void initBinder(WebDataBinder binder){
binder.setValidator(eventValidator);
}
@PostMapping()
public ResponseEntity<EventModel> save(@Valid @RequestBody EventRequest request, BindingResult result){
if(result.hasErrors()){
//some validation
}
//some other logic
}
}
Then i have a EventRequest
pojo:
public class EventRequest{
private String eventName;
@Valid
@NotNull
private List<Event> events;
//setters and getters
}
In my controller, I have 2 types of validation, the InitBinder
, and also java bean validation (JSR-303) that use @NotNull
in EventRequest class.
The problem is, if I have BindingResult result
in the controller, the @NotNull
annotation won't work. And even the cascaded validation in Event
class is not working too.
Why is that, how can I have both 2 types of validation?
Tried to add this but still not working
@Configuration
public class ValidatorConfig {
@Bean
public LocalValidatorFactoryBean defaultValidator() {
return new LocalValidatorFactoryBean();
}
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
}
binder.setValidator(eventValidator);
will replace other registered validators.
Change to:
binder.addValidators(eventValidator);