How to manually trigger spring validation?

前端 未结 1 1205
盖世英雄少女心
盖世英雄少女心 2020-12-10 10:27

The annotated spring validation on fields of a POJO works when it is created from json request body. However, when I create the same object manually (using setters) and want

相关标签:
1条回答
  • 2020-12-10 11:12

    Spring provides full support for the JSR-303 Bean Validation API. This includes convenient support for bootstrapping a JSR-303 implementation as a Spring bean. This allows a javax.validation.Validator to be injected wherever validation is needed in your application.

    Use the LocalValidatorFactoryBean to configure a default JSR-303 Validator as a Spring bean:

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

    The basic configuration above will trigger JSR-303 to initialize using its default bootstrap mechanism. A JSR-303 provider, such as Hibernate Validator, is expected to be present in the classpath and will be detected automatically.

    5.7.2.1 Injecting a Validator

    LocalValidatorFactoryBean implements both javax.validation.Validator and org.springframework.validation.Validator. You may inject a reference to one of these two interfaces into beans that need to invoke validation logic.

    Inject a reference to javax.validation.Validator if you prefer to work with the JSR-303 API directly:

    // JSR-303 Validator
    import javax.validation.Validator;
    
    @Service
    public class MyService {
    
        @Autowired
        private Validator validator;
    
    }
    

    Inject a reference to org.springframework.validation.Validator if your bean requires the Spring Validation API:

    // Spring Validator
    import org.springframework.validation.Validator;
    
    @Service
    public class MyService {
    
        @Autowired
        private Validator validator;
    
    }
    

    Here is a well exaplained example Using JSR 303 with "classic" Spring Validators (enter the SpringValidatorAdapter)

    This link is very helpful. Wrapping javax.validation.Validator in org.springframework.validation.beanvalidation.SpringValidatorAdapter helped deal with errors consistently. Can you add this as an answer so that I can accept it

    and Spring doc here

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