Autowiring a service into a validator

前端 未结 2 546
时光说笑
时光说笑 2020-12-15 09:50

This example is a bit contrived; I\'ve simplified it to remove extraneous details and to focus on the problem I am having. I have a validator that looks like this:



        
相关标签:
2条回答
  • 2020-12-15 10:21

    In Spring, you need to obtain ValidatorFactory (or Validator itself) via LocalValidatorFactoryBean instead of Validation.buildDefaultValidatorFactory(), as described in the reference.

    @Autowired
    Validator validator;
    
    @RequestMapping 
    public void checkUsername(Model model, User user) { 
        Set<ConstraintViolation<User>> constraintViolations = validator.validateProperty(user, "username"); 
        model.addAttribute("error", constraintViolations.size() > 0); 
    } 
    

    -

    <bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
    

    EDIT: But perhaps the better way to do it is to use Spring MVC's automatic validation with @Valid annotation:

    @RequestMapping  
    public void checkUsername(Model model, @Valid User user, BindingResult result) {  
        if (result.hasErrors()) {   
            ...
        }
    }
    

    This also requires <mvc:annotation-driven/> in the config.

    0 讨论(0)
  • 2020-12-15 10:29

    Instead of creating a new validator, you have to autowire or inject it to controller. The NPE from the service not being injected as your validator is not being created/managed by spring.

    0 讨论(0)
提交回复
热议问题