简体   繁体   English

如何在外部对象上使用beanvalidation?

[英]How to use beanvalidation on external objects?

I'd like to use BeanValidation mechanisms like @NotNull, @Size etc on a big object. 我想在一个大对象上使用像@NotNull @NotNull, @Size等BeanValidation机制。 I only want to validate certain properties that I make use of. 我只想验证我使用的某些属性。

The object comes from an external library, so I cannot add annotations to it's getters. 该对象来自外部库,因此我无法为其getter添加注释。 Neither would I like to manually create my own object and make a deep copy of the project. 我也不想手动创建自己的对象并制作项目的深层副本。

Is there any change I could use a BeanValidation framework on a class that I cannot change? 是否有任何变化我可以在类上使用BeanValidation框架,我无法更改? Similar to: 如同:

class MyValidator {
    @NotNull
    static String getUsername(ExternalClass ext) {
         return ext.getUser();
    }
}

As answered by mvb13, you can use the XML based configuration for this. 正如mvb13所解释的那样,您可以使用基于XML的配置。 If you're working with Hibernate Validator as your BV provider you also can leverage the API for programmatic constraint declaration : 如果您正在使用Hibernate Validator作为您的BV提供者,您还可以利用API进行编程约束声明

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

ConstraintMapping constraintMapping = configuration.createConstraintMapping();

constraintMapping
    .type( ExternalClass.class )
        .property( "someProperty", FIELD )
            .constraint( new NotNullDef() )
            .constraint( new SizeDef().min( 2 ).max( 14 ) )
    .type( AnotherExternalClass.class )
        .property( "anotherProperty", METHOD )
            .constraint( new NotNullDef() );

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

Exists variant of using xml config to describe validation rules. 存在使用xml config来描述验证规则的变体。 This is how it is implemented in Hibernate https://docs.jboss.org/hibernate/validator/4.0.1/reference/en/html/validator-xmlconfiguration.html In this case you don't need to change source code. 这是它在Hibernate中的实现方式https://docs.jboss.org/hibernate/validator/4.0.1/reference/en/html/validator-xmlconfiguration.html在这种情况下,您无需更改源代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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