4

我编写自定义消息插值。我希望 JPA 将使用我的自定义消息插值。在这里http://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html/validator-bootstrapping.html#section-message-interpolator我发现以下描述:

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

Validator validator = factory.getValidator();

但是我应该在哪里写这样的代码?在 init-servlet 的 web.xml 中?我可以在persistance.xml 中提供这样的代码吗?

PS我复制并粘贴代码。在我的情况下

ValueFormatterMessageInterpolator(configuration.getDefaultMessageInterpolator()))

会改变这样的事情

CustomMessageInterpolator(configuration.getDefaultMessageInterpolator()))

另请参阅如何使用 Hibernate Validator 动态解析消息参数?

4

1 回答 1

1

The JSR-303 bean validation framework provides the possibility to configure the validatation framework via XML.

E.g. META-INF/validation.xml

See chapter

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

of the spec 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 persistence jar (META-INF/validation.xml) and it should work.

Depending on your deployment packaging (e.g. EAR) it might be necessary to put it in a shared lib in the EAR's lib folder.

The hibernate documentation says:

The key to enable XML configuration for Hibernate Validator is the file validation.xml. If this file exists in the classpath its configuration will be applied when the ValidationFactory gets created. Example 4.1, “validation-configuration-1.0.xsd” shows a model view of the xsd valiation.xml has to adhere to.

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

于 2013-08-20T08:10:37.643 回答