问题
I have many jsf2 web projects that use the same validation constraints.
- Can I put all these constraints in a shared library?
- If yes, can I supply traslations for the validation messages?
- If yes, how can I achieve it in a standard way?
- Is the following package structure correct?
commons.jar library:
commons.jar
|
+ library
| |
| + CustomConstraint1.class
| + CustomConstraint2.class
|
+ ValidationMessages_it.properties
+ ValidationMessages_en.properties
+ ValidationMessages_de.properties
回答1:
Your bundling is right for a standalone jar. It won't work if you drop this jar into a ear/war with it's own constraints and a ValidationMessages.properties in the root of the classpath.
回答2:
- Can I put all these constraints in a shared library?
Yes, you can.
- If yes, can I supply traslations for the validation messages?
Yes, this is also possible.
- If yes, how can I achieve it in a standard way?
For example, you have a constraint like this:
package com.example.constraints;
@Target({
ElementType.FIELD,
ElementType.PARAMETER,
ElementType.METHOD
})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {
FooValidator.class
})
public @interface Foo
{
String message() default "{com.example.constraints.Foo.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Specify a ValidationMessages.properties
in the root of your class path (For the application's default language). For extra locales you should specify a ValidationMessages_[locale].properties
file. For a Dutch locale it should be ValidationMessages_nl.properties
.
Then in those files you define your message variable as a key and the message as a value like this:
com.example.constraints.Foo.message=Foo is not valid
来源:https://stackoverflow.com/questions/11683708/bean-validation-constraints-in-a-shared-library