spring-mvc - 在 spring mvc 应用程序中动态添加约束到 hibernate 验证器

标签 spring-mvc hibernate-validator

我在我的 spring mvc 应用程序中使用 hibernate 验证器。通过以下简单的步骤,我就可以进行验证。

  1. pom.xml 更改以添加休眠验证器。
  2. 用一些约束注释了 Bean。
  3. 使用 @Valid 注释 Controller 方法参数。
  4. 处理了MethodArgumentNotValidException

我不想向 bean 添加约束,而是想动态地将它们添加到 bean 中。这种动态添加需要在应用程序启动期间发生,并且只需发生一次。

在 hibernate 验证器文档中,我看到以下代码片段。

constraintMapping.type( Car.class ).property( "manufacturer", FIELD ).constraint( new NotNullDef() )

我的问题是,如何获取此 ConstraintMapping 实例的句柄?我看到 Spring 通过 LocalValidatorFactoryBean 实例化了 hibernate 验证器。 感谢您的帮助。

最佳答案

您可以从HibernateValidatorConfiguration获取它 - http://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html_single/#section-programmatic-api

HibernateValidatorConfiguration configuration = Validation
        .byProvider( HibernateValidator.class )
        .configure();

ConstraintMapping constraintMapping = configuration.createConstraintMapping();

constraintMapping
    .type( Car.class )
        .property( "manufacturer", FIELD )
            .constraint( new NotNullDef() )
        .property( "licensePlate", FIELD )
            .ignoreAnnotations()
            .constraint( new NotNullDef() )
            .constraint( new SizeDef().min( 2 ).max( 14 ) )
    .type( RentalCar.class )
        .property( "rentalStation", METHOD )
            .constraint( new NotNullDef() );

Validator validator = configuration.addMapping( constraintMapping )
        .buildValidatorFactory()
        .getValidator();

但这意味着您可能无法使用 LocalValidatorFactoryBean,但您可能可以编写自己的。

关于spring-mvc - 在 spring mvc 应用程序中动态添加约束到 hibernate 验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21617556/

相关文章:

java - 不同主题的 Spring mvc ResourceBundleMessageSource

java - 如何在 Spring Boot 应用程序中实现长轮询 REST 端点?

java - ConstraintValidator 不起作用(我该怎么做?)

java - hibernate validator 奇怪的 IOException : Stream closed

java - Spring 安全: redirect logged user depending on some conditions

java - 当命中 ExceptionMappingAuthenticationFailureHandler 时获取 Controller 类上的用户 ID

java - @ManyToOne 关系的 PK 未插入

java - 在服务层中使用 Spring 进行 Bean 验证

maven-2 - org.hibernate.validator.engine.ConfigurationImpl 的来源

spring-boot - Gradle 选择了错误的依赖版本