Debian Codegraph @

documentation/src/main/asciidoc/ch08.asciidoc

raw
1 [[chapter-bootstrapping]]
2 == Bootstrapping
3
4 In <<section-obtaining-validator>> you already saw one way for creating a Validator instance - via
5 `Validation#buildDefaultValidatorFactory()`. In this chapter you will learn how to use the other
6 methods in `javax.validation.Validation` in order to bootstrap specifically configured validators.
7
8 [[section-retrieving-validator-factory-validator]]
9 === Retrieving `ValidatorFactory` and `Validator`
10
11 You obtain a `Validator` by retrieving a `ValidatorFactory` via one of the static methods on
12 `javax.validation.Validation` and calling `getValidator()` on the factory instance.
13
14 <<example-build-default-validator-factory>> shows how to obtain a validator from the default
15 validator factory:
16
17 [[example-build-default-validator-factory]]
18 .Bootstrapping default `ValidatorFactory` and `Validator`
19 ====
20 [source, JAVA]
21 ----
22 ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
23 Validator validator = factory.getValidator();
24 ----
25 ====
26
27 [TIP]
28 ====
29 The generated `ValidatorFactory` and `Validator` instances are thread-safe and can be cached. As
30 Hibernate Validator uses the factory as context for caching constraint metadata it is recommended to
31 work with one factory instance within an application.
32 ====
33
34 Bean Validation supports working with several providers such as Hibernate Validator within one
35 application. If more than one provider is present on the classpath, it is not guaranteed which one
36 is chosen when creating a factory via `buildDefaultValidatorFactory()`.
37
38 In this case you can explicitly specify the provider to use via `Validation#byProvider()`, passing the
39 provider's `ValidationProvider` class as shown in <<example-using-specific-provider>>.
40
41 [[example-using-specific-provider]]
42 .Bootstrapping `ValidatorFactory` and Validator using a specific provider
43 ====
44 [source, JAVA]
45 ----
46 ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
47 .configure()
48 .buildValidatorFactory();
49 Validator validator = validatorFactory.getValidator();
50 ----
51 ====
52
53 Note that the configuration object returned by `configure()` allows to specifically customize the
54 factory before calling `buildValidatorFactory()`. The available options are discussed later in this
55 chapter.
56
57 Similarly you can retrieve the default validator factory for configuration which is demonstrated in
58 <<example-configuring-default-provider>>.
59
60 [[example-configuring-default-provider]]
61 .Retrieving the default `ValidatorFactory` for configuration
62 ====
63 [source, JAVA]
64 ----
65 ValidatorFactory validatorFactory = Validation.byDefaultProvider()
66 .configure()
67 .buildValidatorFactory();
68 Validator validator = validatorFactory.getValidator();
69 ----
70 ====
71
72 [NOTE]
73 ====
74 If a `ValidatorFactory` instance is no longer in use, it should be disposed by calling
75 `ValidatorFactory#close()`. This will free any resources possibly allocated by the factory.
76 ====
77
78 [[section-validation-provider-resolver]]
79 ==== `ValidationProviderResolver`
80
81 By default, available Bean Validation providers are discovered using the
82 link:http://docs.oracle.com/javase/6/docs/technotes/guides/jar/jar.html#Service%20Provider[Java
83 Service Provider] mechanism.
84
85 For that purpose, each provider includes the file _META-
86 INF/services/javax.validation.spi.ValidationProvider_, containing the fully qualified classname of
87 its `ValidationProvider` implementation. In the case of Hibernate Validator this is
88 `org.hibernate.validator.HibernateValidator`.
89
90 Depending on your environment and its classloading specifics, provider discovery via the Java's
91 service loader mechanism might not work. In this case you can plug in a custom
92 `ValidationProviderResolver` implementation which performs the provider retrieval. An example is OSGi,
93 where you could implement a provider resolver which uses OSGi services for provider discovery.
94
95 To use a custom provider resolver pass it via `providerResolver()` as shown shown in
96 <<example-using-custom-validation-provider-resolver>>.
97
98 [[example-using-custom-validation-provider-resolver]]
99 .Using a custom `ValidationProviderResolver`
100 ====
101 [source, JAVA]
102 ----
103 package org.hibernate.validator.referenceguide.chapter08;
104
105 public class OsgiServiceDiscoverer implements ValidationProviderResolver {
106
107 @Override
108 public List<ValidationProvider<?>> getValidationProviders() {
109 //...
110 }
111 }
112 ----
113
114 [source, JAVA]
115 ----
116 ValidatorFactory validatorFactory = Validation.byDefaultProvider()
117 .providerResolver( new OsgiServiceDiscoverer() )
118 .configure()
119 .buildValidatorFactory();
120 Validator validator = validatorFactory.getValidator();
121 ----
122 ====
123
124 [[section-configuring-validator-factory]]
125 === Configuring a `ValidatorFactory`
126
127 By default validator factories retrieved from `Validation` and any validators they create are
128 configured as per the XML descriptor _META-INF/validation.xml_ (see <<chapter-xml-configuration>>),
129 if present.
130
131 If you want to disable the XML based configuration, you can do so by invoking
132 `Configuration#ignoreXmlConfiguration()`.
133
134 The different values of the XML configuration can be accessed via
135 `Configuration#getBootstrapConfiguration()`. This can for instance be helpful if you want to integrate
136 Bean Validation into a managed environment and want to create managed instances of the objects
137 configured via XML.
138
139 Using the fluent configuration API, you can override one or more of the settings when bootstrapping
140 the factory. The following sections show how to make use of the different options. Note that the
141 `Configuration` class exposes the default implementations of the different extension points which can
142 be useful if you want to use these as delegates for your custom implementations.
143
144 [[section-validator-factory-message-interpolator]]
145 ==== `MessageInterpolator`
146
147 Message interpolators are used by the validation engine to create user readable error messages from
148 constraint message descriptors.
149
150 In case the default message interpolation algorithm described in <<chapter-message-interpolation>>
151 is not sufficient for your needs, you can pass in your own implementation of the `MessageInterpolator`
152 interface via `Configuration#messageInterpolator()` as shown in
153 <<example-using-custom-message-interpolator>>.
154
155 [[example-using-custom-message-interpolator]]
156 .Using a custom `MessageInterpolator`
157 ====
158 [source, JAVA]
159 ----
160 package org.hibernate.validator.referenceguide.chapter08;
161
162 public class MyMessageInterpolator implements MessageInterpolator {
163
164 @Override
165 public String interpolate(String messageTemplate, Context context) {
166 //...
167 }
168
169 @Override
170 public String interpolate(String messageTemplate, Context context, Locale locale) {
171 //...
172 }
173 }
174 ----
175
176 [source, JAVA]
177 ----
178 ValidatorFactory validatorFactory = Validation.byDefaultProvider()
179 .configure()
180 .messageInterpolator( new MyMessageInterpolator() )
181 .buildValidatorFactory();
182 Validator validator = validatorFactory.getValidator();
183 ----
184 ====
185
186 ==== `TraversableResolver`
187
188 In some cases the validation engine should not access the state of a bean property. The most obvious
189 example for that is a lazily loaded property or association of a JPA entity. Validating this lazy
190 property or association would mean that its state would have to be accessed, triggering a load from
191 the database.
192
193 Which properties can be accessed and which ones not is controlled by querying the
194 `TraversableResolver` interface. <<example-using-custom-traversable-resolver>> shows how to use a
195 custom traversable resolver implementation.
196
197 [[example-using-custom-traversable-resolver]]
198 .Using a custom `TraversableResolver`
199 ====
200 [source, JAVA]
201 ----
202 package org.hibernate.validator.referenceguide.chapter08;
203
204 public class MyTraversableResolver implements TraversableResolver {
205
206 @Override
207 public boolean isReachable(
208 Object traversableObject,
209 Node traversableProperty,
210 Class<?> rootBeanType,
211 Path pathToTraversableObject,
212 ElementType elementType) {
213 //...
214 }
215
216 @Override
217 public boolean isCascadable(
218 Object traversableObject,
219 Node traversableProperty,
220 Class<?> rootBeanType,
221 Path pathToTraversableObject,
222 ElementType elementType) {
223 //...
224 }
225 }
226 ----
227
228 [source, JAVA]
229 ----
230 ValidatorFactory validatorFactory = Validation.byDefaultProvider()
231 .configure()
232 .traversableResolver( new MyTraversableResolver() )
233 .buildValidatorFactory();
234 Validator validator = validatorFactory.getValidator();
235 ----
236 ====
237
238 If no specific traversable resolver has been configured, the default behavior is to consider all properties as reachable and cascadable.
239 When using Hibernate Validator together with a JPA 2 provider such as Hibernate ORM, only those properties will be considered reachable
240 which already have been loaded by the persistence provider and all properties will be considered cascadable.
241
242 ==== `ConstraintValidatorFactory`
243
244 `ConstraintValidatorFactory` is the extension point for customizing how constraint validators are
245 instantiated and released.
246
247 The default `ConstraintValidatorFactory` provided by Hibernate Validator requires a public no-arg
248 constructor to instantiate `ConstraintValidator` instances (see <<section-constraint-validator>>).
249 Using a custom `ConstraintValidatorFactory` offers for example the possibility to use dependency
250 injection in constraint validator implementations.
251
252 To configure a custom constraint validator factory call `Configuration#constraintValidatorFactory()`
253 (see <<example-using-custom-constraint-validator-factory>>.
254
255 [[example-using-custom-constraint-validator-factory]]
256 .Using a custom `ConstraintValidatorFactory`
257 ====
258 [source, JAVA]
259 ----
260 package org.hibernate.validator.referenceguide.chapter08;
261
262 public class MyConstraintValidatorFactory implements ConstraintValidatorFactory {
263
264 @Override
265 public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) {
266 //...
267 }
268
269 @Override
270 public void releaseInstance(ConstraintValidator<?, ?> instance) {
271 //...
272 }
273 }
274 ----
275
276 [source, JAVA]
277 ----
278 ValidatorFactory validatorFactory = Validation.byDefaultProvider()
279 .configure()
280 .constraintValidatorFactory( new MyConstraintValidatorFactory() )
281 .buildValidatorFactory();
282 Validator validator = validatorFactory.getValidator();
283 ----
284 ====
285
286 [WARNING]
287 ====
288 Any constraint implementations relying on `ConstraintValidatorFactory` behaviors specific to an
289 implementation (dependency injection, no no-arg constructor and so on) are not considered portable.
290 ====
291
292 [NOTE]
293 ====
294 `ConstraintValidatorFactory` implementations should not cache validator instances as the state of each
295 instance can be altered in the `initialize()` method.
296 ====
297
298 [[section-parameter-name-provider]]
299 ==== `ParameterNameProvider`
300
301 In case a method or constructor parameter constraint is violated, the `ParameterNameProvider`
302 interface is used to retrieve the parameter name and make it available to the user via the
303 property path of the constraint violation.
304
305 The default implementation returns parameter names in the form of `arg0`, `arg1` etc, while custom
306 implementations can retrieve the parameter names using methods such as parameter annotations,
307 debug symbols, or Java 8 reflection.
308
309 An implementation for retrieving the parameter names using reflection in Java 8 is provided with
310 `ReflectionParameterNameProvider`. For this parameter name provider to work, the
311 source must be compiled using the `–parameters` compiler argument. Otherwise, the provider will
312 return synthetic names in the form of `arg0`, `arg1`, etc.
313
314 To use `ReflectionParameterNameProvider` or another custom provider either pass an instance of
315 the provider during bootstrapping as shown in <<example-using-custom-parameter-name-provider>>,
316 or specify the fully qualified class name of the provider as value for
317 the `<parameter-name-provider>` element in the _META-INF/validation.xml_ file
318 (see <<section-configuration-validation-xml>>). This is demonstrated in
319 <<example-using-custom-parameter-name-provider>>.
320
321 [[example-using-custom-parameter-name-provider]]
322 .Using a custom `ParameterNameProvider`
323 ====
324 [source, JAVA]
325 ----
326 package org.hibernate.validator.referenceguide.chapter08;
327
328 public class MyParameterNameProvider implements ParameterNameProvider {
329
330 @Override
331 public List<String> getParameterNames(Constructor<?> constructor) {
332 //...
333 }
334
335 @Override
336 public List<String> getParameterNames(Method method) {
337 //...
338 }
339 }
340 ----
341
342 [source, JAVA]
343 ----
344 ValidatorFactory validatorFactory = Validation.byDefaultProvider()
345 .configure()
346 .parameterNameProvider( new MyParameterNameProvider() )
347 .buildValidatorFactory();
348 Validator validator = validatorFactory.getValidator();
349 ----
350 ====
351
352
353 [TIP]
354 ====
355 Hibernate Validator comes with a custom `ParameterNameProvider` implementation based on the
356 link:https://github.com/paul-hammant/paranamer/[ParaNamer] library which provides several ways
357 for obtaining parameter names at runtime. Refer to <<section-paranamer-parameternameprovider>>
358 to learn more about this specific implementation.
359 ====
360
361 ==== Adding mapping streams
362
363 As discussed earlier you can configure the constraints applying for your Java beans using XML based
364 constraint mappings.
365
366 Besides the mapping files specified in _META-INF/validation.xml_ you can add further mappings via
367 `Configuration#addMapping()` (see <<example-adding-mapping-streams>>). Note that the passed input
368 stream(s) must adhere to the XML schema for constraint mappings presented in
369 <<section-mapping-xml-constraints>>.
370
371 [[example-adding-mapping-streams]]
372 .Adding constraint mapping streams
373 ====
374 [source, JAVA]
375 ----
376 InputStream constraintMapping1 = ...;
377 InputStream constraintMapping2 = ...;
378 ValidatorFactory validatorFactory = Validation.byDefaultProvider()
379 .configure()
380 .addMapping( constraintMapping1 )
381 .addMapping( constraintMapping2 )
382 .buildValidatorFactory();
383 Validator validator = validatorFactory.getValidator();
384 ----
385 ====
386
387 You should close any passed input stream after the validator factory has been created.
388
389 [[section-provider-specific-settings]]
390 ==== Provider-specific settings
391
392 Via the configuration object returned by `Validation#byProvider()` provider specific options can be
393 configured.
394
395 In case of Hibernate Validator this e.g. allows you to enable the fail fast mode and pass one or
396 more programmatic constraint mappings as demonstrated in
397 <<example-hibernate-validator-specific-options>>.
398
399 [[example-hibernate-validator-specific-options]]
400 .Setting Hibernate Validator specific options
401 ====
402 [source, JAVA]
403 ----
404 ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
405 .configure()
406 .failFast( true )
407 .addMapping( (ConstraintMapping) null )
408 .buildValidatorFactory();
409 Validator validator = validatorFactory.getValidator();
410 ----
411 ====
412
413 Alternatively, provider-specific options can be passed via `Configuration#addProperty()`. Hibernate
414 Validator supports enabling the fail fast mode that way, too:
415
416 [[example-hibernate-validator-specific-option-via-addproperty]]
417 .Enabling a Hibernate Validator specific option via `addProperty()`
418 ====
419 [source, JAVA]
420 ----
421 ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
422 .configure()
423 .addProperty( "hibernate.validator.fail_fast", "true" )
424 .buildValidatorFactory();
425 Validator validator = validatorFactory.getValidator();
426 ----
427 ====
428
429 Refer to <<section-fail-fast>> and <<section-programmatic-api>> to learn more about the fail fast
430 mode and the constraint declaration API.
431
432 [[section-configuring-validator]]
433 === Configuring a Validator
434
435 When working with a configured validator factory it can occasionally be required to apply a
436 different configuration to a single `Validator` instance. <<example-using-context>> shows how this can
437 be achieved by calling `ValidatorFactory#usingContext()`.
438
439 [[example-using-context]]
440 .Configuring a `Validator` instance via `usingContext()`
441 ====
442 [source, JAVA]
443 ----
444 ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
445
446 Validator validator = validatorFactory.usingContext()
447 .messageInterpolator( new MyMessageInterpolator() )
448 .traversableResolver( new MyTraversableResolver() )
449 .getValidator();
450 ----
451 ====