Bean Validation constraints in a shared library

守給你的承諾、 提交于 2019-12-11 10:28:50

问题


I have many jsf2 web projects that use the same validation constraints.

  1. Can I put all these constraints in a shared library?
  2. If yes, can I supply traslations for the validation messages?
  3. If yes, how can I achieve it in a standard way?
  4. 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:


  1. Can I put all these constraints in a shared library?

Yes, you can.

  1. If yes, can I supply traslations for the validation messages?

Yes, this is also possible.

  1. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!