Search code examples
javaspringhibernatehibernate-validatorproperties-file

How to inject values from another properties file into ValidationMessages.properties?


I need to change the @NotNull message used by hibernate-validator.

Have successfully done this using a line in ValidationMessages.properties, e.g: javax.validation.constraints.NotNull.message=my validation message.

However, this isn't quite what's needed. Will spare the details about why but all these messages should originate from a single messages.properties file, whose purpose is not only for validation but other messages as well.

Let's say messages.properties initially contains a single property CCCI_0001=my generic message. Is it possible to somehow substitute this property value from messages.properties into a placeholder in ValidationMessages.properties?


Solution

  • What you can do is bootstrap your ValidatorFactory with a custom MessageInterpolator. If you are happy to use a Hibernate Validator specific feature, you can use a ResourceBundleLocator - see http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-custom-message-interpolation. It looks somewhat like this:

    Validator validator = Validation.byDefaultProvider()
            .configure()
            .messageInterpolator(
                    new ResourceBundleMessageInterpolator(
                            new PlatformResourceBundleLocator( "MyMessages" )
                    )
            )
            .buildValidatorFactory()
            .getValidator();