简体   繁体   中英

Java bean validation not working with web init binder

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM