0
# Configuration and Bootstrap
1
2
Bootstrap and configure Hibernate Validator with comprehensive options for controlling validation behavior, including fail-fast modes, method constraint validation rules, Expression Language feature levels, temporal validation tolerance, resource bundle locations, and predefined scope validation for build-time optimization.
3
4
## Capabilities
5
6
### Standard Validation Provider
7
8
Bootstrap Hibernate Validator as the validation provider for full-scope validation with runtime constraint discovery.
9
10
```java { .api }
11
package org.hibernate.validator;
12
13
import jakarta.validation.Configuration;
14
import jakarta.validation.ValidatorFactory;
15
import jakarta.validation.spi.BootstrapState;
16
import jakarta.validation.spi.ConfigurationState;
17
import jakarta.validation.spi.ValidationProvider;
18
19
/**
20
* Default implementation of ValidationProvider within Hibernate Validator.
21
* Main entry point for bootstrapping with full scope validation.
22
*/
23
class HibernateValidator implements ValidationProvider<HibernateValidatorConfiguration> {
24
/**
25
* Create Hibernate Validator specific configuration.
26
*
27
* @param state bootstrap state
28
* @return Hibernate Validator configuration
29
*/
30
HibernateValidatorConfiguration createSpecializedConfiguration(BootstrapState state);
31
32
/**
33
* Create generic Jakarta Validation configuration.
34
*
35
* @param state bootstrap state
36
* @return generic configuration
37
*/
38
Configuration<?> createGenericConfiguration(BootstrapState state);
39
40
/**
41
* Build ValidatorFactory from configuration state.
42
*
43
* @param configurationState configuration state
44
* @return validator factory
45
*/
46
ValidatorFactory buildValidatorFactory(ConfigurationState configurationState);
47
}
48
```
49
50
**Usage Example:**
51
52
```java
53
import jakarta.validation.Validation;
54
import jakarta.validation.ValidatorFactory;
55
import org.hibernate.validator.HibernateValidator;
56
57
// Bootstrap using Hibernate Validator provider
58
ValidatorFactory factory = Validation
59
.byProvider(HibernateValidator.class)
60
.configure()
61
.buildValidatorFactory();
62
```
63
64
### Base Configuration Interface
65
66
Base interface containing all Hibernate-specific configuration options. Should not be used directly - use `HibernateValidatorConfiguration` or `PredefinedScopeHibernateValidatorConfiguration` instead.
67
68
```java { .api }
69
package org.hibernate.validator;
70
71
import jakarta.validation.Configuration;
72
import jakarta.validation.TraversableResolver;
73
import java.time.Duration;
74
import java.util.Locale;
75
import java.util.Set;
76
import org.hibernate.validator.cfg.ConstraintMapping;
77
import org.hibernate.validator.messageinterpolation.ExpressionLanguageFeatureLevel;
78
import org.hibernate.validator.metadata.BeanMetaDataClassNormalizer;
79
import org.hibernate.validator.spi.messageinterpolation.LocaleResolver;
80
import org.hibernate.validator.spi.nodenameprovider.PropertyNodeNameProvider;
81
import org.hibernate.validator.spi.properties.GetterPropertySelectionStrategy;
82
import org.hibernate.validator.spi.resourceloading.ResourceBundleLocator;
83
import org.hibernate.validator.spi.scripting.ScriptEvaluatorFactory;
84
85
/**
86
* Base interface for Hibernate Validator specific configurations.
87
* Provides all Hibernate-specific configuration methods.
88
*
89
* @param <S> The actual type of the configuration
90
*/
91
interface BaseHibernateValidatorConfiguration<S extends BaseHibernateValidatorConfiguration<S>>
92
extends Configuration<S> {
93
94
// Configuration property constants
95
String FAIL_FAST = "hibernate.validator.fail_fast";
96
String ALLOW_PARAMETER_CONSTRAINT_OVERRIDE = "hibernate.validator.allow_parameter_constraint_override";
97
String ALLOW_MULTIPLE_CASCADED_VALIDATION_ON_RESULT = "hibernate.validator.allow_multiple_cascaded_validation_on_result";
98
String ALLOW_PARALLEL_METHODS_DEFINE_PARAMETER_CONSTRAINTS = "hibernate.validator.allow_parallel_method_parameter_constraint";
99
String CONSTRAINT_MAPPING_CONTRIBUTORS = "hibernate.validator.constraint_mapping_contributors";
100
String ENABLE_TRAVERSABLE_RESOLVER_RESULT_CACHE = "hibernate.validator.enable_traversable_resolver_result_cache";
101
String SCRIPT_EVALUATOR_FACTORY_CLASSNAME = "hibernate.validator.script_evaluator_factory";
102
String TEMPORAL_VALIDATION_TOLERANCE = "hibernate.validator.temporal_validation_tolerance";
103
String GETTER_PROPERTY_SELECTION_STRATEGY_CLASSNAME = "hibernate.validator.getter_property_selection_strategy";
104
String PROPERTY_NODE_NAME_PROVIDER_CLASSNAME = "hibernate.validator.property_node_name_provider";
105
String LOCALE_RESOLVER_CLASSNAME = "hibernate.validator.locale_resolver";
106
String CONSTRAINT_EXPRESSION_LANGUAGE_FEATURE_LEVEL = "hibernate.validator.constraint_expression_language_feature_level";
107
String CUSTOM_VIOLATION_EXPRESSION_LANGUAGE_FEATURE_LEVEL = "hibernate.validator.custom_violation_expression_language_feature_level";
108
String SHOW_VALIDATED_VALUE_IN_TRACE_LOGS = "hibernate.validator.show_validated_value_in_trace_logs";
109
String FAIL_FAST_ON_PROPERTY_VIOLATION = "hibernate.validator.fail_fast_on_property_violation";
110
111
/**
112
* Get the default ResourceBundleLocator for message interpolation.
113
* Retrieves the bundle "ValidationMessages" by default.
114
*
115
* @return the default ResourceBundleLocator, never null
116
*/
117
ResourceBundleLocator getDefaultResourceBundleLocator();
118
119
/**
120
* Create a new ConstraintMapping for programmatic constraint configuration.
121
* Must be added via addMapping() after configuration.
122
*
123
* @return new ConstraintMapping instance
124
*/
125
ConstraintMapping createConstraintMapping();
126
127
/**
128
* Get default ValueExtractor implementations per specification.
129
*
130
* @return default ValueExtractor implementations
131
* @since 6.0
132
*/
133
@Incubating
134
Set<jakarta.validation.valueextraction.ValueExtractor<?>> getDefaultValueExtractors();
135
136
/**
137
* Add programmatic constraint mapping to configuration.
138
*
139
* @param mapping constraint mapping to add
140
* @return this configuration for method chaining
141
*/
142
S addMapping(ConstraintMapping mapping);
143
144
/**
145
* Enable or disable fail-fast mode. When enabled, validation stops
146
* on the first constraint violation detected.
147
*
148
* @param failFast true to enable fail-fast, false otherwise
149
* @return this configuration for method chaining
150
*/
151
S failFast(boolean failFast);
152
153
/**
154
* Set class loader for loading user-provided resources including
155
* XML descriptors, classes specified in XML, and ValidationMessages bundle.
156
*
157
* @param externalClassLoader class loader for user resources
158
* @return this configuration for method chaining
159
* @since 5.2
160
*/
161
S externalClassLoader(ClassLoader externalClassLoader);
162
163
/**
164
* Control whether overriding methods can alter parameter constraints.
165
* Default is false (do not allow) per Jakarta Validation specification.
166
*
167
* @param allow true to allow parameter constraint override
168
* @return this configuration for method chaining
169
* @since 5.3
170
*/
171
S allowOverridingMethodAlterParameterConstraint(boolean allow);
172
173
/**
174
* Control whether multiple cascaded validation marks on return values
175
* are allowed in class hierarchy. Default is false (do not allow).
176
*
177
* @param allow true to allow multiple cascaded validation
178
* @return this configuration for method chaining
179
* @since 5.3
180
*/
181
S allowMultipleCascadedValidationOnReturnValues(boolean allow);
182
183
/**
184
* Control whether parallel methods can define parameter constraints.
185
* Default is false (do not allow) per Jakarta Validation specification.
186
*
187
* @param allow true to allow parallel method parameter constraints
188
* @return this configuration for method chaining
189
* @since 5.3
190
*/
191
S allowParallelMethodsDefineParameterConstraints(boolean allow);
192
193
/**
194
* Enable or disable per-validation-call caching of TraversableResolver results.
195
* Default is true (caching enabled).
196
*
197
* @param enabled true to enable caching
198
* @return this configuration for method chaining
199
* @since 6.0.3
200
*/
201
S enableTraversableResolverResultCache(boolean enabled);
202
203
/**
204
* Set custom ScriptEvaluatorFactory for script constraint evaluation.
205
*
206
* @param scriptEvaluatorFactory script evaluator factory
207
* @return this configuration for method chaining
208
* @since 6.0.3
209
*/
210
@Incubating
211
S scriptEvaluatorFactory(ScriptEvaluatorFactory scriptEvaluatorFactory);
212
213
/**
214
* Set acceptable margin of error for temporal constraint validation.
215
*
216
* @param temporalValidationTolerance tolerance duration
217
* @return this configuration for method chaining
218
* @since 6.0.5
219
*/
220
@Incubating
221
S temporalValidationTolerance(Duration temporalValidationTolerance);
222
223
/**
224
* Set payload passed to constraint validators. If called multiple times,
225
* only the last payload is propagated.
226
*
227
* @param constraintValidatorPayload payload for validators
228
* @return this configuration for method chaining
229
* @since 6.0.8
230
*/
231
@Incubating
232
S constraintValidatorPayload(Object constraintValidatorPayload);
233
234
/**
235
* Set getter property selection strategy for JavaBean getter detection.
236
*
237
* @param getterPropertySelectionStrategy strategy implementation
238
* @return this configuration for method chaining
239
* @since 6.1.0
240
*/
241
@Incubating
242
S getterPropertySelectionStrategy(GetterPropertySelectionStrategy getterPropertySelectionStrategy);
243
244
/**
245
* Set property node name provider for property path construction.
246
*
247
* @param propertyNodeNameProvider name provider implementation
248
* @return this configuration for method chaining
249
* @since 6.1.0
250
*/
251
@Incubating
252
S propertyNodeNameProvider(PropertyNodeNameProvider propertyNodeNameProvider);
253
254
/**
255
* Set supported locales for this ValidatorFactory.
256
* Can force initialization of resource bundles at bootstrap.
257
*
258
* @param locales set of supported locales
259
* @return this configuration for method chaining
260
* @since 6.1.1
261
*/
262
@Incubating
263
S locales(Set<Locale> locales);
264
265
/**
266
* Set supported locales for this ValidatorFactory (varargs version).
267
*
268
* @param locales supported locales
269
* @return this configuration for method chaining
270
* @since 6.1.1
271
*/
272
@Incubating
273
default S locales(Locale... locales) {
274
return locales(new java.util.HashSet<>(java.util.Arrays.asList(locales)));
275
}
276
277
/**
278
* Set default locale for constraint violation message interpolation.
279
*
280
* @param defaultLocale default locale
281
* @return this configuration for method chaining
282
* @since 6.1.1
283
*/
284
@Incubating
285
S defaultLocale(Locale defaultLocale);
286
287
/**
288
* Set locale resolver for dynamic locale resolution during message interpolation.
289
*
290
* @param localeResolver locale resolver implementation
291
* @return this configuration for method chaining
292
* @since 6.1.1
293
*/
294
@Incubating
295
S localeResolver(LocaleResolver localeResolver);
296
297
/**
298
* Set bean metadata class normalizer.
299
*
300
* @param beanMetaDataClassNormalizer normalizer implementation
301
* @return this configuration for method chaining
302
*/
303
@Incubating
304
S beanMetaDataClassNormalizer(BeanMetaDataClassNormalizer beanMetaDataClassNormalizer);
305
306
/**
307
* Set Expression Language feature level for constraint message interpolation.
308
* Controls which EL features are available for static constraint messages.
309
*
310
* @param expressionLanguageFeatureLevel feature level
311
* @return this configuration for method chaining
312
* @since 6.2
313
*/
314
@Incubating
315
S constraintExpressionLanguageFeatureLevel(ExpressionLanguageFeatureLevel expressionLanguageFeatureLevel);
316
317
/**
318
* Set Expression Language feature level for custom violation message interpolation.
319
* Controls which EL features are available for dynamic custom violations.
320
*
321
* @param expressionLanguageFeatureLevel feature level
322
* @return this configuration for method chaining
323
* @since 6.2
324
*/
325
@Incubating
326
S customViolationExpressionLanguageFeatureLevel(ExpressionLanguageFeatureLevel expressionLanguageFeatureLevel);
327
328
/**
329
* Enable or disable inclusion of validated values in trace logs.
330
* Default is false (values not printed) to protect sensitive data.
331
*
332
* @param enabled true to show values in trace logs
333
* @return this configuration for method chaining
334
* @since 8.0
335
*/
336
@Incubating
337
S showValidatedValuesInTraceLogs(boolean enabled);
338
339
/**
340
* Enable or disable skipping of class-level constraints when property-level
341
* constraints generate violations. When enabled, class-level validation
342
* is skipped if any property violation occurs.
343
*
344
* @param failFastOnPropertyViolation true to skip class-level constraints
345
* @return this configuration for method chaining
346
* @since 9.0
347
*/
348
@Incubating
349
S failFastOnPropertyViolation(boolean failFastOnPropertyViolation);
350
}
351
```
352
353
**Usage Example:**
354
355
```java
356
import jakarta.validation.Validation;
357
import jakarta.validation.ValidatorFactory;
358
import org.hibernate.validator.HibernateValidator;
359
import org.hibernate.validator.HibernateValidatorConfiguration;
360
import org.hibernate.validator.messageinterpolation.ExpressionLanguageFeatureLevel;
361
import java.time.Duration;
362
import java.util.Locale;
363
364
HibernateValidatorConfiguration configuration = Validation
365
.byProvider(HibernateValidator.class)
366
.configure();
367
368
configuration
369
.failFast(true)
370
.enableTraversableResolverResultCache(false)
371
.temporalValidationTolerance(Duration.ofMillis(100))
372
.constraintExpressionLanguageFeatureLevel(ExpressionLanguageFeatureLevel.BEAN_PROPERTIES)
373
.locales(Locale.US, Locale.UK, Locale.FRANCE)
374
.defaultLocale(Locale.US)
375
.showValidatedValuesInTraceLogs(false)
376
.failFastOnPropertyViolation(false);
377
378
ValidatorFactory factory = configuration.buildValidatorFactory();
379
```
380
381
### Standard Configuration
382
383
Primary configuration interface for standard Hibernate Validator usage with full-scope validation.
384
385
```java { .api }
386
package org.hibernate.validator;
387
388
/**
389
* Uniquely identifies Hibernate Validator in Bean Validation bootstrap strategy.
390
* Contains Hibernate Validator specific configurations for standard usage.
391
* Extends Jakarta Validation Configuration with Hibernate-specific features.
392
*/
393
interface HibernateValidatorConfiguration
394
extends BaseHibernateValidatorConfiguration<HibernateValidatorConfiguration> {
395
// Inherits all methods from BaseHibernateValidatorConfiguration
396
}
397
```
398
399
### Hibernate Validator Factory
400
401
Extension of Jakarta Validation ValidatorFactory with Hibernate-specific features.
402
403
```java { .api }
404
package org.hibernate.validator;
405
406
import jakarta.validation.ValidatorFactory;
407
import java.time.Duration;
408
import org.hibernate.validator.spi.nodenameprovider.PropertyNodeNameProvider;
409
import org.hibernate.validator.spi.properties.GetterPropertySelectionStrategy;
410
import org.hibernate.validator.spi.scripting.ScriptEvaluatorFactory;
411
412
/**
413
* Provides Hibernate Validator extensions to ValidatorFactory.
414
* Access Hibernate-specific factory methods and create Hibernate ValidatorContext.
415
*/
416
interface HibernateValidatorFactory extends ValidatorFactory {
417
/**
418
* Get ScriptEvaluatorFactory configured for this factory.
419
*
420
* @return script evaluator factory
421
*/
422
@Incubating
423
ScriptEvaluatorFactory getScriptEvaluatorFactory();
424
425
/**
426
* Get temporal validation tolerance configured for this factory.
427
*
428
* @return temporal validation tolerance
429
*/
430
@Incubating
431
Duration getTemporalValidationTolerance();
432
433
/**
434
* Get getter property selection strategy configured for this factory.
435
*
436
* @return getter property selection strategy
437
*/
438
@Incubating
439
GetterPropertySelectionStrategy getGetterPropertySelectionStrategy();
440
441
/**
442
* Get property node name provider configured for this factory.
443
*
444
* @return property node name provider
445
*/
446
@Incubating
447
PropertyNodeNameProvider getPropertyNodeNameProvider();
448
449
/**
450
* Create HibernateValidatorContext with Hibernate-specific configuration options.
451
*
452
* @return Hibernate validator context
453
*/
454
@Override
455
HibernateValidatorContext usingContext();
456
}
457
```
458
459
**Usage Example:**
460
461
```java
462
import org.hibernate.validator.HibernateValidatorFactory;
463
464
ValidatorFactory factory = // ... obtain factory
465
HibernateValidatorFactory hibernateFactory = factory.unwrap(HibernateValidatorFactory.class);
466
467
// Access Hibernate-specific features
468
Duration tolerance = hibernateFactory.getTemporalValidationTolerance();
469
ScriptEvaluatorFactory scriptFactory = hibernateFactory.getScriptEvaluatorFactory();
470
471
// Create Hibernate-specific validator context
472
HibernateValidatorContext context = hibernateFactory.usingContext();
473
```
474
475
### Hibernate Validator Context
476
477
Per-validator configuration allowing runtime customization of validation behavior.
478
479
```java { .api }
480
package org.hibernate.validator;
481
482
import jakarta.validation.ClockProvider;
483
import jakarta.validation.ConstraintValidatorFactory;
484
import jakarta.validation.MessageInterpolator;
485
import jakarta.validation.ParameterNameProvider;
486
import jakarta.validation.TraversableResolver;
487
import jakarta.validation.ValidatorContext;
488
import jakarta.validation.valueextraction.ValueExtractor;
489
import java.time.Duration;
490
491
/**
492
* Hibernate Validator specific context for creating Validator instances
493
* with additional configuration options beyond standard ValidatorContext.
494
*/
495
interface HibernateValidatorContext extends ValidatorContext {
496
/**
497
* Set message interpolator for this validator.
498
*
499
* @param messageInterpolator message interpolator instance
500
* @return this context for method chaining
501
*/
502
@Override
503
HibernateValidatorContext messageInterpolator(MessageInterpolator messageInterpolator);
504
505
/**
506
* Set traversable resolver for this validator.
507
*
508
* @param traversableResolver traversable resolver instance
509
* @return this context for method chaining
510
*/
511
@Override
512
HibernateValidatorContext traversableResolver(TraversableResolver traversableResolver);
513
514
/**
515
* Set constraint validator factory for this validator.
516
*
517
* @param factory constraint validator factory instance
518
* @return this context for method chaining
519
*/
520
@Override
521
HibernateValidatorContext constraintValidatorFactory(ConstraintValidatorFactory factory);
522
523
/**
524
* Set parameter name provider for this validator.
525
*
526
* @param parameterNameProvider parameter name provider instance
527
* @return this context for method chaining
528
* @since 5.2
529
*/
530
@Override
531
HibernateValidatorContext parameterNameProvider(ParameterNameProvider parameterNameProvider);
532
533
/**
534
* Set clock provider for this validator.
535
*
536
* @param clockProvider clock provider instance
537
* @return this context for method chaining
538
* @since 6.0
539
*/
540
@Override
541
HibernateValidatorContext clockProvider(ClockProvider clockProvider);
542
543
/**
544
* Add value extractor for this validator.
545
*
546
* @param extractor value extractor instance
547
* @return this context for method chaining
548
* @since 6.0
549
*/
550
@Override
551
HibernateValidatorContext addValueExtractor(ValueExtractor<?> extractor);
552
553
/**
554
* Enable or disable fail-fast mode for this validator.
555
* When enabled, validation stops on first violation.
556
*
557
* @param failFast true to enable fail-fast
558
* @return this context for method chaining
559
*/
560
HibernateValidatorContext failFast(boolean failFast);
561
562
/**
563
* Control whether overriding methods can alter parameter constraints.
564
*
565
* @param allow true to allow parameter constraint override
566
* @return this context for method chaining
567
* @since 5.3
568
*/
569
HibernateValidatorContext allowOverridingMethodAlterParameterConstraint(boolean allow);
570
571
/**
572
* Control whether multiple cascaded validation marks are allowed on return values.
573
*
574
* @param allow true to allow multiple cascaded validation
575
* @return this context for method chaining
576
* @since 5.3
577
*/
578
HibernateValidatorContext allowMultipleCascadedValidationOnReturnValues(boolean allow);
579
580
/**
581
* Control whether parallel methods can define parameter constraints.
582
*
583
* @param allow true to allow parallel method parameter constraints
584
* @return this context for method chaining
585
* @since 5.3
586
*/
587
HibernateValidatorContext allowParallelMethodsDefineParameterConstraints(boolean allow);
588
589
/**
590
* Enable or disable TraversableResolver result caching for this validator.
591
*
592
* @param enabled true to enable caching
593
* @return this context for method chaining
594
* @since 6.0.3
595
*/
596
HibernateValidatorContext enableTraversableResolverResultCache(boolean enabled);
597
598
/**
599
* Set temporal validation tolerance for this validator.
600
*
601
* @param temporalValidationTolerance tolerance duration
602
* @return this context for method chaining
603
* @since 6.0.5
604
*/
605
@Incubating
606
HibernateValidatorContext temporalValidationTolerance(Duration temporalValidationTolerance);
607
608
/**
609
* Set payload passed to constraint validators for this validator.
610
*
611
* @param constraintValidatorPayload payload object
612
* @return this context for method chaining
613
* @since 6.0.8
614
*/
615
@Incubating
616
HibernateValidatorContext constraintValidatorPayload(Object constraintValidatorPayload);
617
618
/**
619
* Control whether validated values appear in trace logs for this validator.
620
*
621
* @param enabled true to show values in trace logs
622
* @return this context for method chaining
623
* @since 8.0
624
*/
625
@Incubating
626
HibernateValidatorContext showValidatedValuesInTraceLogs(boolean enabled);
627
628
/**
629
* Enable or disable fail-fast on property violation for this validator.
630
*
631
* @param failFastOnPropertyViolation true to skip class-level constraints
632
* @return this context for method chaining
633
* @since 9.0
634
*/
635
@Incubating
636
HibernateValidatorContext failFastOnPropertyViolation(boolean failFastOnPropertyViolation);
637
}
638
```
639
640
**Usage Example:**
641
642
```java
643
import jakarta.validation.Validator;
644
import org.hibernate.validator.HibernateValidatorContext;
645
import java.time.Duration;
646
647
ValidatorFactory factory = // ... obtain factory
648
HibernateValidatorContext context = factory.unwrap(HibernateValidatorFactory.class)
649
.usingContext();
650
651
Validator validator = context
652
.failFast(true)
653
.temporalValidationTolerance(Duration.ofMillis(50))
654
.constraintValidatorPayload(new MyPayload())
655
.showValidatedValuesInTraceLogs(false)
656
.getValidator();
657
```
658
659
### Predefined Scope Validation
660
661
Validation provider and configuration for predefined scope validation, allowing metadata collection at bootstrap time for performance optimization.
662
663
```java { .api }
664
package org.hibernate.validator;
665
666
import jakarta.validation.spi.BootstrapState;
667
import jakarta.validation.spi.ValidationProvider;
668
import java.util.Set;
669
670
/**
671
* Implementation of ValidationProvider limiting validation to predefined scope.
672
* Allows metadata collection at bootstrap for build-time optimization.
673
*
674
* @since 6.1
675
*/
676
@Incubating
677
class PredefinedScopeHibernateValidator
678
implements ValidationProvider<PredefinedScopeHibernateValidatorConfiguration> {
679
680
PredefinedScopeHibernateValidatorConfiguration createSpecializedConfiguration(BootstrapState state);
681
jakarta.validation.Configuration<?> createGenericConfiguration(BootstrapState state);
682
jakarta.validation.ValidatorFactory buildValidatorFactory(jakarta.validation.spi.ConfigurationState configurationState);
683
}
684
685
/**
686
* Extension of HibernateValidatorConfiguration with methods for defining predefined scope.
687
* Allows specifying which built-in constraints, bean classes, and XML definitions to include.
688
*
689
* @since 6.1
690
*/
691
@Incubating
692
interface PredefinedScopeHibernateValidatorConfiguration
693
extends BaseHibernateValidatorConfiguration<PredefinedScopeHibernateValidatorConfiguration> {
694
695
/**
696
* Define set of built-in constraint annotation types to include in scope.
697
* Only specified constraints will be available for validation.
698
*
699
* @param constraints set of constraint class names (fully qualified)
700
* @return this configuration for method chaining
701
*/
702
@Incubating
703
PredefinedScopeHibernateValidatorConfiguration builtinConstraints(Set<String> constraints);
704
705
/**
706
* Define set of bean classes to initialize metadata for at bootstrap.
707
* Metadata for these classes will be prepared during factory creation.
708
*
709
* @param beanClasses set of bean classes
710
* @return this configuration for method chaining
711
*/
712
@Incubating
713
PredefinedScopeHibernateValidatorConfiguration initializeBeanMetaData(Set<Class<?>> beanClasses);
714
715
/**
716
* Control whether beans and constraints defined only in XML should be included.
717
*
718
* @param include true to include XML-only definitions
719
* @return this configuration for method chaining
720
*/
721
@Incubating
722
PredefinedScopeHibernateValidatorConfiguration includeBeansAndConstraintsDefinedOnlyInXml(boolean include);
723
}
724
725
/**
726
* Extension of HibernateValidatorFactory for predefined scope validation.
727
*
728
* @since 6.1
729
*/
730
@Incubating
731
interface PredefinedScopeHibernateValidatorFactory extends HibernateValidatorFactory {
732
// Inherits all methods from HibernateValidatorFactory
733
}
734
```
735
736
**Usage Example:**
737
738
```java
739
import jakarta.validation.Validation;
740
import jakarta.validation.ValidatorFactory;
741
import org.hibernate.validator.PredefinedScopeHibernateValidator;
742
import org.hibernate.validator.PredefinedScopeHibernateValidatorConfiguration;
743
import java.util.Set;
744
745
// Bootstrap with predefined scope
746
PredefinedScopeHibernateValidatorConfiguration configuration = Validation
747
.byProvider(PredefinedScopeHibernateValidator.class)
748
.configure();
749
750
configuration
751
// Only include specific built-in constraints
752
.builtinConstraints(Set.of(
753
"jakarta.validation.constraints.NotNull",
754
"jakarta.validation.constraints.Size",
755
"org.hibernate.validator.constraints.Length"
756
))
757
// Initialize metadata for specific bean classes at bootstrap
758
.initializeBeanMetaData(Set.of(User.class, Order.class, Product.class))
759
// Include XML-only definitions
760
.includeBeansAndConstraintsDefinedOnlyInXml(true);
761
762
ValidatorFactory factory = configuration.buildValidatorFactory();
763
```
764
765
## Types
766
767
### Bean Metadata Class Normalizer
768
769
```java { .api }
770
package org.hibernate.validator.metadata;
771
772
/**
773
* Defines how the validated class is normalized before being used as the key
774
* to retrieve bean metadata.
775
*
776
* In predefined scope validator factories, all classes that will be validated
777
* must be registered. To validate method calls, frameworks usually generate proxies
778
* to intercept calls. Such proxies might be hard to register as they are generated code.
779
*
780
* This contract allows normalizing the class before obtaining metadata from the
781
* PredefinedScopeBeanMetaDataManager, so only the original bean class needs to be
782
* registered, not the proxy class.
783
*
784
* This also avoids generating unnecessary metadata for proxy classes.
785
*
786
* @since 6.1
787
*/
788
@Incubating
789
interface BeanMetaDataClassNormalizer {
790
/**
791
* Normalizes the provided class as the key used to get bean metadata from
792
* the PredefinedScopeBeanMetaDataManager.
793
*
794
* @param beanClass the original bean class
795
* @param <T> the type of the bean
796
* @return the normalized class
797
*/
798
<T> Class<? super T> normalize(Class<T> beanClass);
799
}
800
```
801
802
**Usage Example:**
803
804
```java
805
import org.hibernate.validator.metadata.BeanMetaDataClassNormalizer;
806
import org.hibernate.validator.PredefinedScopeHibernateValidator;
807
import jakarta.validation.Validation;
808
809
// Custom normalizer that removes proxy suffixes
810
public class ProxyAwareBeanMetaDataClassNormalizer implements BeanMetaDataClassNormalizer {
811
@Override
812
public <T> Class<? super T> normalize(Class<T> beanClass) {
813
// If this is a CGLIB proxy, get the superclass
814
if (beanClass.getName().contains("$$EnhancerByCGLIB$$")) {
815
return beanClass.getSuperclass();
816
}
817
818
// If this is a Javassist proxy, get the superclass
819
if (beanClass.getName().contains("_$$_javassist")) {
820
return beanClass.getSuperclass();
821
}
822
823
// Otherwise return the class as-is
824
return beanClass;
825
}
826
}
827
828
// Configure with custom normalizer
829
ValidatorFactory factory = Validation
830
.byProvider(PredefinedScopeHibernateValidator.class)
831
.configure()
832
.beanMetaDataClassNormalizer(new ProxyAwareBeanMetaDataClassNormalizer())
833
.initializeBeanMetaData(Set.of(User.class, Order.class))
834
.buildValidatorFactory();
835
836
// Now validation will work even with proxy instances
837
User userProxy = createProxiedUser(); // Returns User$$EnhancerByCGLIB$$abc123
838
validator.validate(userProxy); // Uses User.class metadata (not proxy class)
839
```
840