0

I'm using Java Beans validation through hibernate-validation on a JavaFX application, so, without a framework to help with the wiring. I added these dependencies to my project:

compile group: "org.hibernate", name: "hibernate-validator", version: "6.0.2.Final"
compile group: "org.glassfish", name: "javax.el", version: "3.0.1-b08"
compile group: "javax.validation", name: "validation-api", version: "2.0.0.Final"

and I found this works to get modelObject validated:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
validator.validate(modelObject);

My question is, is it bad to create a new factory and validator every time I validate? Should I cache them somewhere and re-use them? How expensive and how multi-threaded are the validators?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622

1 Answers1

1

Is it bad to create new ValidatorFactory each time?

According to the javadoc note, the following is stated:

  • The ValidatorFactory object built by the bootstrap process should be cached and shared amongst Validator consumers.
  • This class is thread-safe.

As of Validator, its implementations also expected to be thread-safe according to javadoc

Working with javax.Validation in Spring

You've tagged your question with 'Spring', therefore a brief notice on working with javax.validation + Spring correctly.

First, use Spring LocalValidatorFactoryBean (as for example answered here), that will take care of necessary caching you're looking for:

@Bean
public javax.validation.Validator localValidatorFactoryBean() {
   return new LocalValidatorFactoryBean();
}

Second, inject Validator instances using Spring as well:

@Autowired
private Validator validator;

You can either let Spring do all the job. For example, to make validation-related annotations work for methods, define

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
    return new MethodValidationPostProcessor();
}

in your Spring application configuration, and then you'll be able to call something like

public void myMethod(@Valid MyValidationAnnotatedType parameter){
    ...
}

public void anotherMethod(@Pattern(regex = "^[A-Za-z]+$") stringParameter) {
    ...
} 

Please refer to Spring documentation for further details

Kostiantyn
  • 1,856
  • 11
  • 13
  • Thank you for the pointers to the JavaDoc... I shouldn't have missed that. Regarding Spring, that was a mistake, so I removed the tag, but the server side is running Spring, so, that'll be useful anyway :) – Pablo Fernandez Aug 28 '17 at 09:50