I have a Java app that contains a dependency. The dependency is a Java library which provides:
javax.validation.Validator
javax.validation.ConstraintValidator
sThe app uses the library's validator to validate the library's POJOs. So far, so good. But the app also composes a new POJO that has the library's POJOs as fields (nested POJOs). The app's POJOs which are composed from the library's POJOs, need validation, so the app also has its own validation messages in a properties file. (While validating one Java object, we may potentially need validation messages from the library and from the app).
private static final ValidatorFactory FACTORY = Validation.byDefaultProvider()
.configure()
.messageInterpolator(new ResourceBundleMessageInterpolator(
new PlatformResourceBundleLocator("MyLibraryValidationMessages")))
.buildValidatorFactory();
How can I validate a single POJO (with nested POJOs inside it) that contains annotations (and their associated ConstraintValidators
) that reference messages from two different resource bundles? Needed: a Validator
that gets messages from two different resource bundles. I'm not using Spring.
We may not need to use resource bundles from properties files at all, since we don't need separate message translations for separate locales. We only need one default message for each error. If we can store all of the messages in code, could that provide a workaround?
One workaround that I have not yet tried, but I think would work, is to ensure that the Resource Bundle names in the library and app are exactly the same, and duplicate/copy all of the messages from the sdk into the app's resource bundle, since if they use the same name, the app's bundle will shadow the library's bundle. But this is sub-optimal because of the duplication of error messages.
I control the code of both the dependency and the app.
I just found the AggregateResourceBundleLocator
that should do the job:
private static final ValidatorFactory FACTORY = Validation.byDefaultProvider()
.configure()
.messageInterpolator(new ResourceBundleMessageInterpolator(
new AggregateResourceBundleLocator(
Arrays.asList("MyLibraryValidationMessages", "MyAppValidationMessages"))))
.buildValidatorFactory();