简体   繁体   中英

How to extend a built-in Hibernate Validator ConstraintValidator

Now I am working on my spring+hibernate application.
I want to overlay validator of @Min annotation and wrote following code:

@Component
public class CustomMinValidator extends MinValidatorForNumber {

    public void initialize() {
        Min min = new Min() {

            @Override
            public String message() {
                return null;  //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public Class<?>[] groups() {
                return new Class<?>[0];
            }

            @Override
            public Class<? extends Payload>[] payload() {
                return null;
            }

            @Override
            public long value() {
                return 150;
            }

            @Override
            public Class<? extends Annotation> annotationType() {
                return null;
            }
        };
        super.initialize(min);
    }
}

But in debug I see that CustomMinValidator#initialize never invokes but MinValidatorForNumber#initialize invokes.

How to overlay standart validator properly ?

You have to "register" your custom constraint validator via a constraint-mapping file - http://beanvalidation.org/1.1/spec/#xml-mapping-constraintdefinition

In your case you also need to set include-existing-validators="true" so that the constraint validator resolution is unique for Numbers s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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