How to set up custom message interpolation using Hibernate?

I am writing custom message interpolation. I want JPA to use my custom message interpolation. Here http://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html/validator-bootstrapping.html#section-message-interpolator I found the following description:

Configuration<?> configuration = Validation.byDefaultProvider().configure(); ValidatorFactory factory = configuration .messageInterpolator(new ValueFormatterMessageInterpolator(configuration.getDefaultMessageInterpolator())) .buildValidatorFactory(); Validator validator = factory.getValidator(); 

but where should I write such code? In web.xml in an init servlet? Can I provide such code in persistance.xml?

PS I copy and paste the code. In my case, the line

 ValueFormatterMessageInterpolator(configuration.getDefaultMessageInterpolator())) 

will be changed to something like this

 CustomMessageInterpolator(configuration.getDefaultMessageInterpolator())) 

see also How to dynamically resolve message settings using Hibernate Validator?

+4
source share
1 answer

The JSR-303 bean validation engine provides the ability to configure validation frameworks via XML.

eg. META-INF/validation.xml

See chapter

4.4.6. XML Configuration: META-INF / validation.xml

specifications for details: http://download.oracle.com/otndocs/jcp/bean_validation-1.0-fr-oth-JSpec/

4.4.6. XML Configuration: META-INF / validation.xml

 <?xml version="1.0" encoding="UTF-8"?> <validation-config xmlns="http://jboss.org/xml/ns/javax/validation/configuration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration validation-configuration-1.0.xsd"> <default-provider>com.acme.ACMEProvider</default-provider> <message-interpolator>com.acme.ACMEAwareMessageInterpolator</message-interpolator> <constraint-mapping>META-INF/validation/order-constraints.xml</constraint-mapping> <constraint-mapping>META-INF/validation/catalog-constraints.xml</constraint-mapping> <constraint-mapping>META-INF/validation/customer-constraints.xml</constraint-mapping> <property name="com.acme.validation.logging">WARN</property> <property name="com.acme.validation.safetyChecking">failOnError</property> </validation-config> 

Package the xml file with your save bank (META-INF / validation.xml) and it should work.

Depending on your deployment packaging (for example, EAR), you may need to place it in a shared folder in the EAR lib folder.

The hibernation documentation says:

The key to enable the XML configuration for the Hibernate Validator is the validation.xml file. If this file exists in the classpath, its configuration will be applied when creating the ValidationFactory. Example 4.1, "validation-configuration-1.0.xsd" shows the model view xsd valiation.xml should adhere to.

http://docs.jboss.org/hibernate/validator/4.0.1/reference/en/html_single/#d0e1867

0
source

Source: https://habr.com/ru/post/1497942/


All Articles