使用spring验证带有内部方法注释的数据

时间:2017-03-22 22:48:45

标签: java spring validation annotations

我是一个春天的新手所以请耐心等待我。但我想知道基于注释的验证是否也可用于非形式方法?我知道BindingResult可以用于输入表单验证。但我有这样的事情:

public class Service{
  @NotBlank
  @Column
  private String name;
}


public class ServiceController{
    @PostMapping
    public Service create() {
        ... some additional code...
        return createServiceObject();
    }

    private Service createServiceObject(){
        ...some additional code...
        Service s = new Service();
        /* I want Not Blank validation for name to get triggered here */
        s.setName(someInputFromForm)
    }
}

我想要根据注释@NotBlank验证名称,而不是像我一样手动检查:name.trim.isEmpty()。这可能吗?

1 个答案:

答案 0 :(得分:1)

如果尚未添加,请将LocalValidatorFactoryBean类的新bean添加到配置中。如果你正在使用java配置,那么就像:

@Configuration
public class AppConfig {

    ...

    @Bean
    public LocalValidatorFactoryBean validatorFactoryBean(){
        return new LocalValidatorFactoryBean();
    }

}

或者,如果您使用的是xml配置,那么:

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

如果您已经在配置中添加了LocalValidatorFactoryBean bean,只需设置此bean的名称(您需要它来进行依赖注入)。

现在您可以将此bean用作验证器:

public class ServiceController{

    @Autowired
    @Qualifier("validatorFactoryBean")
    private LocalValidatorFactoryBean validatorFactoryBean;

    @PostMapping
    public Service create() {
        ... some additional code...
        return createServiceObject();
    }

    private Service createServiceObject(){
        Service service = new Service();
        service.setName(someInputFromForm)

        DataBinder binder = new DataBinder(service);
        binder.addValidators(validatorFactoryBean);
        binder.validate();
        BindingResult result = binder.getBindingResult();
        if(result.hasErrors()){
            // here you can throw exception or do something else
        }
        return service;
    }
}